<commit_before>(function (exports){

	holdJQueryDOMReady();

	var model = createModel();
	var styleModel = createModel();

	exports.UI = {
		initialize         : initialize,
		initializePlugin   : initializePlugin,
        destroyPlugin      : destroyPlugin,
		initStyleMigration : initStyleMigration,
		set                : model.setAndReport,
		get                : model.get,
		toJSON             : model.toJSON,
		onChange           : model.onChange
	};

	function log(){
		var args = ['<ui-lib>'];
		args.push.apply(args,arguments);
		false && console.log.apply(console, args);
	}

    function initialize(initialValues, onModelChange) {
		if(initialize.isInitialized){return;}
		initialize.isInitialized = true;
		initialize.retry = ++initialize.retry || 1;

    	var $rootEl = $('body'); //$('[wix-uilib],[data-wix-uilib]');
    	if ($rootEl.length > 1) {
    		throw new Error('You have more then one wix-uilib element in the DOM.');
    	}
    	applyPremiumItems($rootEl);

		model.setInitialValues(initialValues);
    	onModelChange && model.onChange('*', onModelChange);

		initStyleModelHandling();

    	var elements = $rootEl.andSelf().find('[data-wix-controller], [wix-controller], [wix-ctrl], [data-wix-ctrl]');
    	for (var i = 0; i < elements.length; i++) {
    		try {
    			initializePlugin(elements[i]);
    		} catch (err) {
    			console.log && console.log('Plugin Initialization Error: ' + err.stack, elements[i]);
    		}
    	}

		if(styleModel.applyStyleMigration){
			styleModel.applyStyleMigration();
		}

    	$rootEl.fadeIn(140, function(){
			$(document.body).trigger('uilib-update-scroll-bars');
		});

    }

	function holdJQueryDOMReady(){
		var timeoutTicket;
		if(window.Wix){
			if(Wix.Utils.getViewMode() === 'standalone'){
				setTimeout(function(){
					throw new Error('Standalone mode: Wix style params are not available outside of the "wix editor"');
				},0);
			} else {
				holdReady(true);
				timeoutTicket = setTimeout(function(){
					holdReady(false);
					throw new Error('Style params are not available outside of the "wix editor", if you are in the editor ');
				}, 3333);
				Wix.getStyleParams(function(){
					clearTimeout(timeoutTicket);
					holdReady(false);
				});
			}
		}

		function holdReady(hold){
			window.jQuery && window.jQuery.holdReady && window.jQuery.holdReady( hold );
		}
	}

	function getVendorProductId() {
		try {
			var inst = window.location.search.match(/instance=([^&]+)/);
			return JSON.parse(atob(inst[1].split('.')[1])).vendorProductId || null;
		} catch (err) {
			return null;
		}
	}

	function applyPremiumItems($rootEl){
		var $premium = $rootEl.find('[wix-premium],[data-wix-premium]');
		var $notPremium = $rootEl.find('[wix-not-premium], [data-wix-not-premium]');
		var isPremium = getVendorProductId();
		if(isPremium){
			$premium.show();
			$notPremium.remove();
		} else {
			$premium.remove();
			$notPremium.show();
		}
	}

	function getAttribute(element, attr) {
		var val = element.getAttribute(attr);
		if (!val) {
			val = element.getAttribute('data-' + attr);
		}
		return val;
	}

    function initializePlugin(element, overrideOptions) {
        var ctrl = getAttribute(element, 'wix-controller') || getAttribute(element, 'wix-ctrl') ;
		var ctrlName = getCtrlName(ctrl);
		var options = getOptions(element, ctrl);
		applyPlugin(element, ctrlName, overrideOptions || options);
    }

    function destroyPlugin(element) {
        var ctrl = getAttribute(element, 'wix-controller') || getAttribute(element, 'wix-ctrl') ;
        var pluginName = getCtrlName(ctrl);
        var wixModel = getAttribute(element, 'wix-model');
		var $el = $(element);
		var plugin = $el.data('plugin_'+pluginName);

        if(wixModel){
            $el.off();
			$el.find('*').off();
			$el.remove();
			plugin.destroy && plugin.destroy();
            delete model.props[wixModel];
            model.handlers = [];
            model.reporters = {};
        }
    }

	function applyPlugin(element, pluginName, options) {
		pluginName = fixPluginName(pluginName);
		if ($.fn[pluginName]) {
			log('initializing ' + pluginName, options);
			$(element)[pluginName](options);
		} else {
			console.error('Plugin ' + pluginName + ' does not exist');
		}
		var param = setUpStyleParams(element, pluginName);
		var model = setUpModel(element, pluginName);
		if(param && model){
			throw new Error('You cannot use wix-param in conjunction with wix-model, only one of them can be used per component.');
		}
	}

	function setUpStyleParams(element, pluginName){
		var wixStyleParam = getAttribute(element, 'wix-param');
		if(wixStyleParam){
			styleModel.bindKeyToPlugin(element, pluginName, wixStyleParam);
		}
		return wixStyleParam;
	}

	function setUpModel(element, pluginName){
		var wixModel = getAttribute(element, 'wix-model');
		if(wixModel){
			model.bindKeyToPlugin(element, pluginName, wixModel);
		}
		return wixModel;
	}

	function evalOptions(options){
		 try{
			return (new Function('return '+ options + ';'))()
		 }catch(e){
			throw new Error('Options for plugin are not valid: ' + options);
		 }
	}

	function fixPluginName(pluginName){
		return pluginName;
	}

	function getOptions(element, ctrl){
		var options = getOptionsFormCtrl(ctrl);
		if (!options) {
			options = getAttribute(element, 'wix-options');
		}
		return evalOptions(options) || {};
	}

    function getOptionsFormCtrl(ctrl) {
		var index = ctrl.indexOf(':');
        if (index !== -1) {
            return ctrl.substr(index + 1);
        }
		return false;
    }

    function getCtrlName(ctrl) {
		var index = ctrl.indexOf(':');
        if (index !== -1) {
            return ctrl.substr(0, index);
        }
		return ctrl;
    }

	function createModel() {
		var model = {
			props : {},
			handlers : [],
			reporters : {},
			isReporting : true,
			get : function (modelKey) {
				if (!model.props.hasOwnProperty(modelKey)) {
					throw new Error('There is no "' + modelKey + '" in this model. try to define "wix-model" in your markup.');
				}
				return model.props[modelKey];
			},
			set : function (modelKey, value, silent, report, plugin) {
				var ignoreSet = false;
				if (!model.props.hasOwnProperty(modelKey)) {
					throw new Error('There is no "' + modelKey + '" in this model. try to define "wix-model" in your markup.');
				}
				if(value && value._model_ignore_set_){
					delete value._model_ignore_set_;
					ignoreSet = true;
				}
				var oldValue = model.props[modelKey];
				if (oldValue !== value) {
					model.props[modelKey] = value;
					if (!silent) {
						model.trigger(modelKey, value);
					}
					if(ignoreSet){return}
									//if(report){
					model.triggerReporters(modelKey, value, plugin);
									//}
				}
			},
			setAndReport : function (modelKey, value, isSilent) {
				model.set(modelKey, value, !!isSilent || false, true);
			},
			setInitialValues : function (initialValues) {
				$.extend(model.props, initialValues);
			},
			bindKeyToPlugin : function (element, pluginName, modelKey) {
				var $el = $(element);
				var plugin = $el.data('plugin_' + pluginName);
				if (!plugin) {
					throw new Error('wix-model is not supported in this plugin "' + pluginName + '"')
				}
				var initValue = model.props[modelKey];
				if (initValue !== undefined) {
					plugin.setValue && plugin.setValue(initValue);
					model.props[modelKey] = plugin.getValue ? plugin.getValue() : initValue;
				} else {
					initValue = plugin.getValue ? plugin.getValue() : undefined;
					model.props[modelKey] = initValue;
				}
				$el.on(pluginName + '.change', function (e, data) {
					model.set(modelKey, data, false, false, plugin);
				});
				model.reporters[modelKey] = model.reporters[modelKey] || [];
				function setValueFromReport(value) {
					plugin.setValue && plugin.setValue(value);
				}
				setValueFromReport.plugin = plugin;
				model.reporters[modelKey].push(setValueFromReport);
			},
			onChange : function (key, fn) {
				if (typeof fn !== 'function') {
					throw new Error(key + ': You must provide fn as handler to the Model change event.');
				}
				model.handlers.push({
					fn : fn,
					key : key
				});
			},
			trigger : function (modelKey, value) {
				for (var i = 0; i < model.handlers.length; i++) {
					try {
						var handler = model.handlers[i];
						if (handler.key === '*' || handler.key === modelKey) {
							handler.fn.call(model, value, modelKey);
						}
					} catch (err) {
						setTimeout(function () {
							throw err;
						}, 0);
					}
				}
			},
			triggerReporters : function (modelKey, value, plugin) {
				if (!model.isReporting) {
					return;
				}
				var reportes = this.reporters[modelKey];
				for (var i = 0; i < reportes.length; i++) {
					var reporter = reportes[i];
					if(reporter.plugin === plugin){
						continue;
					}
					try {
						reporter.call(model, value, modelKey);
					} catch (err) {
						setTimeout(function () {
							throw err;
						}, 0);
					}
				}
			},
			toJSON : function () {
				return $.extend({}, model.props);
			}
		};

		return model;

	}

	/////////////////////////////////////////////////
	/////////////////////STYLE///////////////////////
	/////////////////////////////////////////////////

	function initStyleModelHandling(){
		if(window.Wix){

			var style = Wix.Settings.getStyleParams();

			if(!styleModel.applyStyleMigration){
				var styles;
				try{
					styles = flattenStyles(style);
				}catch(err){
					setTimeout(function(){
						throw err
					},0)
					styles = {};
				}
				styleModel.setInitialValues(styles);

			}

			styleModel.onChange('*', function(value, name){
				//order matters font is like number.
				if(isFontParam(value)){
					Wix.Settings.setFontParam(name, {value: value});
				} else if(isNumberParam(value)){
					Wix.Settings.setNumberParam(name, {value:getNumberParamValue(value)});
				} else if(Object.prototype.toString.call(value).match('Boolean')){
					Wix.Settings.setBooleanParam(name, {value:value});
				} else if(value && (value.hasOwnProperty('color') || value.cssColor || value.rgba)) {
					Wix.Settings.setColorParam(name, {value:value});
				}
			});

		}

		function isFontParam(value){
			return isNumberParam(value) && value.fontParam === true ? true : false
		}

		function isNumberParam(value){
			if(value instanceof Number || typeof value === 'number' || (!isNaN(+value.index) && value.value)){
				return true;
			}
			return false;
		}

		function getNumberParamValue(value){
			return ( value.index || value.index === 0 ) ? value.index : value;
		}

	}

	function initStyleMigration(initValues){
		styleModel.applyStyleMigration = function(){
			for(var key in initValues){
				if(initValues.hasOwnProperty(key)){
					styleModel.set(key, initValues[key]);
				}
			}
		}
	}

	function flattenStyles(style){
		style = style || {};
		var mergedStyle = {};
		//when there will be more types we should merge them
		for(var prop in style.colors){
			if(style.colors.hasOwnProperty(prop)){
				if(style.colors[prop].themeName && style.colors[prop].value.indexOf('rgba')===0){

					var opacity = style.colors[prop].value.match(/,([^),]+)\)/);
					opacity = (opacity ? (+opacity[1]) : 1);

					mergedStyle[prop] = {
						color : {
							reference : style.colors[prop].themeName,
							value : style.colors[prop].value
						},
						rgba : style.colors[prop].value,
						opacity : opacity
					};
				}else{
					mergedStyle[prop] = style.colors[prop].themeName || style.colors[prop].value;
				}
			}
		}
		for(var prop in style.numbers){
			if(style.numbers.hasOwnProperty(prop)){
				mergedStyle[prop] = style.numbers[prop];
			}
		}
		for(var prop in style.booleans){
			if(style.booleans.hasOwnProperty(prop)){
				mergedStyle[prop] = style.booleans[prop];
			}
		}
		for(var prop in style.fonts){
			if(style.fonts.hasOwnProperty(prop)){
				mergedStyle[prop] = style.fonts[prop];
			}
		}
		return mergedStyle;
	}
	/////////////////////////////////////////////////
	/////////////////////////////////////////////////
	/////////////////////////////////////////////////

})(window.Wix || window);

<commit_msg>add style namespace to Wix.UI<commit_after>(function (exports){

	holdJQueryDOMReady();

	var model = createModel();
	var styleModel = createModel();

	exports.UI = {
		initialize         : initialize,
		initializePlugin   : initializePlugin,
        destroyPlugin      : destroyPlugin,
		initStyleMigration : initStyleMigration,
		set                : model.setAndReport,
		get                : model.get,
		toJSON             : model.toJSON,
		onChange           : model.onChange,
		styles             : {
			set: styleModel.set
			get: styleModel.get
			onChange: styleModel.onChange
		}
	};

	function log(){
		var args = ['<ui-lib>'];
		args.push.apply(args,arguments);
		false && console.log.apply(console, args);
	}

    function initialize(initialValues, onModelChange) {
		if(initialize.isInitialized){return;}
		initialize.isInitialized = true;
		initialize.retry = ++initialize.retry || 1;

    	var $rootEl = $('body'); //$('[wix-uilib],[data-wix-uilib]');
    	if ($rootEl.length > 1) {
    		throw new Error('You have more then one wix-uilib element in the DOM.');
    	}
    	applyPremiumItems($rootEl);

		model.setInitialValues(initialValues);
    	onModelChange && model.onChange('*', onModelChange);

		initStyleModelHandling();

    	var elements = $rootEl.andSelf().find('[data-wix-controller], [wix-controller], [wix-ctrl], [data-wix-ctrl]');
    	for (var i = 0; i < elements.length; i++) {
    		try {
    			initializePlugin(elements[i]);
    		} catch (err) {
    			console.log && console.log('Plugin Initialization Error: ' + err.stack, elements[i]);
    		}
    	}

		if(styleModel.applyStyleMigration){
			styleModel.applyStyleMigration();
		}

    	$rootEl.fadeIn(140, function(){
			$(document.body).trigger('uilib-update-scroll-bars');
		});

    }

	function holdJQueryDOMReady(){
		var timeoutTicket;
		if(window.Wix){
			if(Wix.Utils.getViewMode() === 'standalone'){
				setTimeout(function(){
					throw new Error('Standalone mode: Wix style params are not available outside of the "wix editor"');
				},0);
			} else {
				holdReady(true);
				timeoutTicket = setTimeout(function(){
					holdReady(false);
					throw new Error('Style params are not available outside of the "wix editor", if you are in the editor ');
				}, 3333);
				Wix.getStyleParams(function(){
					clearTimeout(timeoutTicket);
					holdReady(false);
				});
			}
		}

		function holdReady(hold){
			window.jQuery && window.jQuery.holdReady && window.jQuery.holdReady( hold );
		}
	}

	function getVendorProductId() {
		try {
			var inst = window.location.search.match(/instance=([^&]+)/);
			return JSON.parse(atob(inst[1].split('.')[1])).vendorProductId || null;
		} catch (err) {
			return null;
		}
	}

	function applyPremiumItems($rootEl){
		var $premium = $rootEl.find('[wix-premium],[data-wix-premium]');
		var $notPremium = $rootEl.find('[wix-not-premium], [data-wix-not-premium]');
		var isPremium = getVendorProductId();
		if(isPremium){
			$premium.show();
			$notPremium.remove();
		} else {
			$premium.remove();
			$notPremium.show();
		}
	}

	function getAttribute(element, attr) {
		var val = element.getAttribute(attr);
		if (!val) {
			val = element.getAttribute('data-' + attr);
		}
		return val;
	}

    function initializePlugin(element, overrideOptions) {
        var ctrl = getAttribute(element, 'wix-controller') || getAttribute(element, 'wix-ctrl') ;
		var ctrlName = getCtrlName(ctrl);
		var options = getOptions(element, ctrl);
		applyPlugin(element, ctrlName, overrideOptions || options);
    }

    function destroyPlugin(element) {
        var ctrl = getAttribute(element, 'wix-controller') || getAttribute(element, 'wix-ctrl') ;
        var pluginName = getCtrlName(ctrl);
        var wixModel = getAttribute(element, 'wix-model');
		var $el = $(element);
		var plugin = $el.data('plugin_'+pluginName);

        if(wixModel){
			plugin.destroy && plugin.destroy();
			$el.off();
			$el.find('*').off();
			$el.remove();
            delete model.props[wixModel];
            model.handlers = [];
            model.reporters = {};
        }
    }

	function applyPlugin(element, pluginName, options) {
		pluginName = fixPluginName(pluginName);
		if ($.fn[pluginName]) {
			log('initializing ' + pluginName, options);
			$(element)[pluginName](options);
		} else {
			console.error('Plugin ' + pluginName + ' does not exist');
		}
		var param = setUpStyleParams(element, pluginName);
		var model = setUpModel(element, pluginName);
		if(param && model){
			throw new Error('You cannot use wix-param in conjunction with wix-model, only one of them can be used per component.');
		}
	}

	function setUpStyleParams(element, pluginName){
		var wixStyleParam = getAttribute(element, 'wix-param');
		if(wixStyleParam){
			styleModel.bindKeyToPlugin(element, pluginName, wixStyleParam);
		}
		return wixStyleParam;
	}

	function setUpModel(element, pluginName){
		var wixModel = getAttribute(element, 'wix-model');
		if(wixModel){
			model.bindKeyToPlugin(element, pluginName, wixModel);
		}
		return wixModel;
	}

	function evalOptions(options){
		 try{
			return (new Function('return '+ options + ';'))()
		 }catch(e){
			throw new Error('Options for plugin are not valid: ' + options);
		 }
	}

	function fixPluginName(pluginName){
		return pluginName;
	}

	function getOptions(element, ctrl){
		var options = getOptionsFormCtrl(ctrl);
		if (!options) {
			options = getAttribute(element, 'wix-options');
		}
		return evalOptions(options) || {};
	}

    function getOptionsFormCtrl(ctrl) {
		var index = ctrl.indexOf(':');
        if (index !== -1) {
            return ctrl.substr(index + 1);
        }
		return false;
    }

    function getCtrlName(ctrl) {
		var index = ctrl.indexOf(':');
        if (index !== -1) {
            return ctrl.substr(0, index);
        }
		return ctrl;
    }

	function createModel() {
		var model = {
			props : {},
			handlers : [],
			reporters : {},
			isReporting : true,
			get : function (modelKey) {
				if (!model.props.hasOwnProperty(modelKey)) {
					throw new Error('There is no "' + modelKey + '" in this model. try to define "wix-model" in your markup.');
				}
				return model.props[modelKey];
			},
			set : function (modelKey, value, silent, report, plugin) {
				var ignoreSet = false;
				if (!model.props.hasOwnProperty(modelKey)) {
					throw new Error('There is no "' + modelKey + '" in this model. try to define "wix-model" in your markup.');
				}
				if(value && value._model_ignore_set_){
					delete value._model_ignore_set_;
					ignoreSet = true;
				}
				var oldValue = model.props[modelKey];
				if (oldValue !== value) {
					model.props[modelKey] = value;
					if (!silent) {
						model.trigger(modelKey, value);
					}
					if(ignoreSet){return}
									//if(report){
					model.triggerReporters(modelKey, value, plugin);
									//}
				}
			},
			setAndReport : function (modelKey, value, isSilent) {
				model.set(modelKey, value, !!isSilent || false, true);
			},
			setInitialValues : function (initialValues) {
				$.extend(model.props, initialValues);
			},
			bindKeyToPlugin : function (element, pluginName, modelKey) {
				var $el = $(element);
				var plugin = $el.data('plugin_' + pluginName);
				if (!plugin) {
					throw new Error('wix-model is not supported in this plugin "' + pluginName + '"')
				}
				var initValue = model.props[modelKey];
				if (initValue !== undefined) {
					plugin.setValue && plugin.setValue(initValue);
					model.props[modelKey] = plugin.getValue ? plugin.getValue() : initValue;
				} else {
					initValue = plugin.getValue ? plugin.getValue() : undefined;
					model.props[modelKey] = initValue;
				}
				$el.on(pluginName + '.change', function (e, data) {
					model.set(modelKey, data, false, false, plugin);
				});
				model.reporters[modelKey] = model.reporters[modelKey] || [];
				function setValueFromReport(value) {
					plugin.setValue && plugin.setValue(value);
				}
				setValueFromReport.plugin = plugin;
				model.reporters[modelKey].push(setValueFromReport);
			},
			onChange : function (key, fn) {
				if (typeof fn !== 'function') {
					throw new Error(key + ': You must provide fn as handler to the Model change event.');
				}
				model.handlers.push({
					fn : fn,
					key : key
				});
			},
			trigger : function (modelKey, value) {
				for (var i = 0; i < model.handlers.length; i++) {
					try {
						var handler = model.handlers[i];
						if (handler.key === '*' || handler.key === modelKey) {
							handler.fn.call(model, value, modelKey);
						}
					} catch (err) {
						setTimeout(function () {
							throw err;
						}, 0);
					}
				}
			},
			triggerReporters : function (modelKey, value, plugin) {
				if (!model.isReporting) {
					return;
				}
				var reportes = this.reporters[modelKey];
				for (var i = 0; i < reportes.length; i++) {
					var reporter = reportes[i];
					if(reporter.plugin === plugin){
						continue;
					}
					try {
						reporter.call(model, value, modelKey);
					} catch (err) {
						setTimeout(function () {
							throw err;
						}, 0);
					}
				}
			},
			toJSON : function () {
				return $.extend({}, model.props);
			}
		};

		return model;

	}

	/////////////////////////////////////////////////
	/////////////////////STYLE///////////////////////
	/////////////////////////////////////////////////

	function initStyleModelHandling(){
		if(window.Wix){

			var style = Wix.Settings.getStyleParams();

			if(!styleModel.applyStyleMigration){
				var styles;
				try{
					styles = flattenStyles(style);
				}catch(err){
					setTimeout(function(){
						throw err
					},0)
					styles = {};
				}
				styleModel.setInitialValues(styles);

			}

			styleModel.onChange('*', function(value, name){
				//order matters font is like number.
				if(isFontParam(value)){
					Wix.Settings.setFontParam(name, {value: value});
				} else if(isNumberParam(value)){
					Wix.Settings.setNumberParam(name, {value:getNumberParamValue(value)});
				} else if(Object.prototype.toString.call(value).match('Boolean')){
					Wix.Settings.setBooleanParam(name, {value:value});
				} else if(value && (value.hasOwnProperty('color') || value.cssColor || value.rgba)) {
					Wix.Settings.setColorParam(name, {value:value});
				}
			});

		}

		function isFontParam(value){
			return isNumberParam(value) && value.fontParam === true ? true : false
		}

		function isNumberParam(value){
			if(value instanceof Number || typeof value === 'number' || (!isNaN(+value.index) && value.value)){
				return true;
			}
			return false;
		}

		function getNumberParamValue(value){
			return ( value.index || value.index === 0 ) ? value.index : value;
		}

	}

	function initStyleMigration(initValues){
		styleModel.applyStyleMigration = function(){
			for(var key in initValues){
				if(initValues.hasOwnProperty(key)){
					styleModel.set(key, initValues[key]);
				}
			}
		}
	}

	function flattenStyles(style){
		style = style || {};
		var mergedStyle = {};
		//when there will be more types we should merge them
		for(var prop in style.colors){
			if(style.colors.hasOwnProperty(prop)){
				if(style.colors[prop].themeName && style.colors[prop].value.indexOf('rgba')===0){

					var opacity = style.colors[prop].value.match(/,([^),]+)\)/);
					opacity = (opacity ? (+opacity[1]) : 1);

					mergedStyle[prop] = {
						color : {
							reference : style.colors[prop].themeName,
							value : style.colors[prop].value
						},
						rgba : style.colors[prop].value,
						opacity : opacity
					};
				}else{
					mergedStyle[prop] = style.colors[prop].themeName || style.colors[prop].value;
				}
			}
		}
		for(var prop in style.numbers){
			if(style.numbers.hasOwnProperty(prop)){
				mergedStyle[prop] = style.numbers[prop];
			}
		}
		for(var prop in style.booleans){
			if(style.booleans.hasOwnProperty(prop)){
				mergedStyle[prop] = style.booleans[prop];
			}
		}
		for(var prop in style.fonts){
			if(style.fonts.hasOwnProperty(prop)){
				mergedStyle[prop] = style.fonts[prop];
			}
		}
		return mergedStyle;
	}
	/////////////////////////////////////////////////
	/////////////////////////////////////////////////
	/////////////////////////////////////////////////

})(window.Wix || window);

<|endoftext|>


<commit_before>// Usage
// author=$(node ./getSlackUser.js)
// or
// author=$(curl –silent -L 'https://raw.githubusercontent.com/debitoor/teamcity-merge/master/getSlackUser.js' | node)

const { execSync } = require('child_process');
const assert = require('assert');

assert(process.env.SLACK_TOKEN, 'process.env.SLACK_TOKEN should be specified');

//Map of emails -> slack user name
const emailsMap = {
	'eagleeyes91@gmail.com': 'eagleeye',
	'bogdan.bele@yahoo.com': 'bogdan',
	'anton.mamant@gmail.com': 'mamant',
	'mpush@inbox.ru': 'mpushkin',
	'jp@jonatanpedersen.com': 'jonatanpedersen',
	'kollner@gmail.com': 'kollner',
	'hiller@live.dk': 'hilleer',
	'alexeymalyarov@gmail.com': 'lex',
	'mfbeast@mail.ru': 'mpushkin',
	'niklasgundlev@gmail.com': 'niklas',
	'dgulkovskiy@gmail.com': 'dima',
	'zygimantas.butas@gmail.com': 'ashtrus'
};

const email = execSync('git log --pretty=format:\'%ae\' -n 1', {encoding: 'utf-8'});
if (email === 'debitoor-bot@debitoor.com') {
	console.log('TeamCity');
	process.exit(0);
}
const usersJSON = execSync(`curl -X POST "https://slack.com/api/users.list?token=${process.env.SLACK_TOKEN}" -s`);
const users = JSON.parse(usersJSON);
const slackUser = emailsMap[email];

const user = users.members.find((m) =>
	m.name === slackUser || m.profile.email === email
);
if(!user) {
	console.log(`${slackUser}|${email} (could not find this slack-username or email in slack?! Fix it here: https://github.com/debitoor/teamcity-merge/blob/master/getSlackUser.js)`);
	process.exit(0);
}
console.log(`<@${user.id}|${slackUser}>`);
<commit_msg>Update zygi<commit_after>// Usage
// author=$(node ./getSlackUser.js)
// or
// author=$(curl –silent -L 'https://raw.githubusercontent.com/debitoor/teamcity-merge/master/getSlackUser.js' | node)

const { execSync } = require('child_process');
const assert = require('assert');

assert(process.env.SLACK_TOKEN, 'process.env.SLACK_TOKEN should be specified');

//Map of emails -> slack user name
const emailsMap = {
	'eagleeyes91@gmail.com': 'eagleeye',
	'bogdan.bele@yahoo.com': 'bogdan',
	'anton.mamant@gmail.com': 'mamant',
	'mpush@inbox.ru': 'mpushkin',
	'jp@jonatanpedersen.com': 'jonatanpedersen',
	'kollner@gmail.com': 'kollner',
	'hiller@live.dk': 'hilleer',
	'alexeymalyarov@gmail.com': 'lex',
	'mfbeast@mail.ru': 'mpushkin',
	'niklasgundlev@gmail.com': 'niklas',
	'dgulkovskiy@gmail.com': 'dima',
	'zygimantas.butas@gmail.com': 'zygi'
};

const email = execSync('git log --pretty=format:\'%ae\' -n 1', {encoding: 'utf-8'});
if (email === 'debitoor-bot@debitoor.com') {
	console.log('TeamCity');
	process.exit(0);
}
const usersJSON = execSync(`curl -X POST "https://slack.com/api/users.list?token=${process.env.SLACK_TOKEN}" -s`);
const users = JSON.parse(usersJSON);
const slackUser = emailsMap[email];

const user = users.members.find((m) =>
	m.name === slackUser || m.profile.email === email
);
if(!user) {
	console.log(`${slackUser}|${email} (could not find this slack-username or email in slack?! Fix it here: https://github.com/debitoor/teamcity-merge/blob/master/getSlackUser.js)`);
	process.exit(0);
}
console.log(`<@${user.id}|${slackUser}>`);
<|endoftext|>


<commit_before>// HybridPrint
// a JavaScript library on synquery.
// require: jQuery > 1.7.0,
//        : jquery.jqcanvo.js (jQuery plug-in)
//        : jquery.EasySvg.js (jQuery plug-in)

// jquery.jqcanvo.js
ECDB.Include('dxGHe1C0');

// jquery.EasySvg.js
ECDB.Include('wpJeBam7');

function HybridPrint(w, h, o) {

  o = $.extend({
    canvas_id: 'hp_canvas',
    svg_id: 'hp_svg',
    appendTo: $('body'),
    unit: 'px' // TODO "mm"
  }, o);

  var hp = this;

  this._width = w, this._height = h, this._unit = o.unit;
  this.$wrapper = $('<div/>').addClass('hybridprint wrapper');

  // canvas
  if(o.canvas_id) {
    this.$canvas = $('<canvas/>').attr({
      id: o.canvas_id,
      width: w,
      height: h
    }), this.$canvas.appendTo(this.wrapper());
    this._canvo = this.$canvas.canvo();
  }

  // svg
  if(o.svg_id) {
    this._svg = new Svg({
      id: o.svg_id,
      width: w,
      height: h
    }), this._svg.appendTo(this.wrapper());
  }

  // iframe for printing
  var $ifr = this.$iframe = $('<iframe/>');
  var $dfd = this.$dfd = new $.Deferred();

  this.$div = $('<div/>').appendTo(o.appendTo).css({
    opacity: 0
  }).append(this.$iframe);

  $ifr.ready(function() {
    var win = $ifr.get(0).contentWindow, doc = win.document;
    var sty = '@page {';
    sty += 'size: ';
    sty += (o.size ? o.size: hp._width + hp.unit + ' ' + hp._height + hp.unit)
      + ';';
    sty += 'margin: ';
    sty += '0;';
    sty += '}';
    doc.body.style.margin = 0;
    $(doc.head).append($('<style type="text/css" media="print"/>').text(sty));
    $(doc.body).append(hp.wrapper());
    $dfd.resolve(), $dfd = null;
  });

};

(function() {

  var HybridProtos = {
    wrapper: wrapper
  };
  for( var i in HybridProtos)
    HybridPrint.prototype[i] = HybridProtos[i];

  var HybridProtosAsync = { // return this.
    line: line,
    rect: rect,
    circle: circle,
    ellipse: ellipse,
    text: text,
    image: image,
    print: print,
    remove: remove
  };
  for( var i in HybridProtosAsync)
    HybridPrint.prototype[i] = (function(i) {
      return function() {
        var hp = this, args = arguments;
        $.when(hp.$dfd).done(function() {
          HybridProtosAsync[i].apply(hp, args);
        });
        return hp;
      };
    })(i);

  function wrapper() {
    return this.$wrapper;
  }

  function line(x1, y1, x2, y2, o) {
    o = setCapitalizedKey($.extend({
      x1: x1,
      y1: y1,
      x2: x2,
      y2: y2,
      border: '1px solid #444'
    }, o));
    adoptBorder(o);

    var w = o.x2 === null ? o.x1: Math.abs(o.x1 - o.x2);
    o = calcAlign(this, w, ['x1', 'x2'], o);
    this._svg.line(o);
  }

  function rect(x, y, w, h, o) {
    o = setCapitalizedKey($.extend({
      x: x,
      y: y,
      width: w,
      height: h,
      border: '1px solid #444',
      background: 'transparent'
    }, o));
    adoptBorder(o);
    adoptBackground(o);

    if(isNaN(parseInt(o.x)) && !o.align)
      o.align = o.x;
    o = calcAlign(this, o.width, ['x', 'w'], o);
    this._svg.rect(o);
  };

  function circle(cx, cy, r, o) {
    o = setCapitalizedKey($.extend({
      cx: cx,
      cy: cy,
      r: r,
      border: '1px solid #444',
      background: 'transparent'
    }, o));
    adoptBorder(o);
    adoptBackground(o);

    o = calcAlign(this, parseInt(o.r) * 2 || o.r, ['cx', 'r'], o);
    this._svg.circle(o);
  }

  function ellipse(cx, cy, rx, ry, o) {
    o = setCapitalizedKey($.extend({
      cx: cx,
      cy: cy,
      rx: rx,
      ry: ry,
      border: '1px solid #444',
      background: 'transparent'
    }, o));
    adoptBorder(o);
    adoptBackground(o);

    o = calcAlign(this, parseInt(o.rx) * 2 || o.rx, ['cx', 'rx'], o);
    this._svg.ellipse(o);
  }

  function text(t, o) {
    o = setCapitalizedKey($.extend({
      x: 0,
      y: 0,
      color: '#444',
      'font-size': '10.5px',
      'font-family': 'serif'
    }, o));
    adoptColor(o);

    var item = this._svg.text(t, o);

    // chrome's getComputedTextLength is not correct when letter-spacing is set.
    var w = item.getComputedTextLength(), c = item.getNumberOfChars();
    var ls = parseInt(o['letter-spacing']) || 0;

    calcAlign(this, w + (c - 1) * ls, true, o, item);
  }

  function image(href, o) {
    o = setCapitalizedKey($.extend({
      x: 0,
      y: 0,
      width: '100px',
      height: '100px',
    }, o));

    var iw = o['image-width'] || o.width;
    if(iw && /%/.test(o.width))
      iw = iw * (parseFloat(o.width) / 100);
    if(!iw)
      throw new Error('image-width must be set for: ' + href);

    o = calcAlign(this, iw, ['x', 'w'], o);
    this._svg.image(href, o);
  }

  function setCapitalizedKey(o) {
    $.each(o, function(k, v) {
      if(/([A-Z])/.test(k))
        o[k.replace(RegExp.$1, '-' + RegExp.$1.toLowerCase())] = v;
    });
    return o;
  }

  function errAnalyzingFailure(type) {
    return type + ' analyzing failure: ';
  }

  function adoptColor(o) {
    var rgb = null, alp = null, pre = null;
    try {
      rgb = codeToRgb(o.color).join();
      alp = o.alpha, pre = alp ? 'rgba': 'rgb';
    } catch(e) {
      console.warn(errAnalyzingFailure('Color') + o.color);
      console.warn(e);
    };
    if(!o.fill)
      o.fill = pre ? pre + "(" + rgb + (alp ? ',' + alp: '') + ")": o.color;
  }

  function adoptBackground(o) {
    var rgb = null, alp = null, pre = null;

    try {
      if(!/transparent/.test(o.background)) {
        rgb = codeToRgb(o.background).join();
        alp = o.alpha, pre = alp ? 'rgba': 'rgb';
      }
    } catch(e) {
      console.warn(errAnalyzingFailure('Background') + o.background);
      console.warn(e);
    };
    if(!o.fill)
      o.fill = pre ? pre + "(" + rgb + (alp ? ',' + alp: '') + ")"
        : o.background;
  }

  function adoptBorder(o) {
    var bdr = null, rgb = null, alp = null, pre = null;
    try {
      bdr = o.border.split(/\s/), rgb = codeToRgb(bdr[2]).join();
      alp = o.alpha, pre = alp ? 'rgba': 'rgb';
    } catch(e) {
      console.warn(errAnalyzingFailure('Border') + o.border);
      console.warn(e);
    }
    if(!o.stroke)
      o.stroke = pre ? pre + "(" + rgb + (alp ? ',' + alp: '') + ")": bdr[2];
    if(!o['stroke-width'])
      o['stroke-width'] = String(bdr[0]).replace(/px/, '');
  }

  function calcAlign(hp, w, keys, o, item) {

    var margin = null, align = null, left = null;

    o = $.extend({}, o);

    var left_key = 'x';
    if($.isArray(keys)) {
      if(keys.indexOf('x1') != -1)
        left_key = 'x1';
      else if(keys.indexOf('cx') != -1)
        left_key = 'cx';
    };

    if(o.align)
      align = o.align;
    else if(isNaN(parseInt(o[left_key])))
      align = o[left_key], o[left_key] = 0;

    if(!align)
      return o;

    margin = o.margin;
    if(!$.isArray(margin))
      switch(align) {
      case 'center':
        margin = [o.margin, o.margin];
        break;
      case 'right':
        margin = [null, o.margin];
        break;
      }

    margin.forEach(function(v, i) {
      margin[i] = parseInt(margin[i]) ? parseInt(margin[i]): 0;
    });

    switch(align) {
    case 'center':
      if(w === 'auto')
        w = hp._width - margin[0] - margin[1];
      left = margin[0] + (hp._width - margin[0] - margin[1] - w) / 2;
      break;
    case 'right':
      left = margin[0] + (hp._width - margin[0] - margin[1] - w);
      break;
    default:
      left = margin[0];
    }

    var fn = item ? function(k, v) {
      item.setAttribute(k, v);
    }: function(k, v) {
      o[k] = v;
    };

    if(keys == true)
      fn('x', left);
    else
      keys.forEach(function(k) {
        if(k == 'x')
          return fn('x', left);
        if(k == 'x1')
          return fn('x1', left);
        if(k == 'x2')
          return fn('x2', left + w);
        if(k == 'cx')
          return fn('cx', left + w / 2);
        if(k == 'w')
          return fn('width', w);
        if(k == 'r' || k == 'rx')
          return fn(k, w / 2);
      });

    return o;

  }

  function print() {
    if(this.$iframe)
      this.$iframe.get(0).contentWindow.print();
    if(this.$div.parent().is('body'))
      this.$div.remove();
  }

  function remove() {
    this.$div.remove();
  }

  // utilities >>
  function codeToRgb(code) {
    var ccode = codeAdjust(code).replace(/^#/, '');
    return [parseInt(ccode.slice(0, 2), '16'),
      parseInt(ccode.slice(2, 4), '16'), parseInt(ccode.slice(4, 6), '16')];
  }

  function codeAdjust(code) {
    if(code.substr(0, 3) == 'rgb')
      return code.replace(/-/g, ',');
    if(!(code.charAt(0) == '#' && (code.length == 4 || code.length == 7)))
      throw new Error([' - illegal color code.(code = ', code, ')'].join(""));
    if(code.length == 4)
      code = [code[0], code[1], code[1], code[2], code[2], code[3], code[3]]
          .join("");
    return code;
  }

})();
<commit_msg>slight bug fix<commit_after>// HybridPrint
// a JavaScript library on synquery.
// require: jQuery > 1.7.0,
//        : jquery.jqcanvo.js (jQuery plug-in)
//        : EasySvg.js (javascript plug-in)

function HybridPrint(w, h, o) {

  o = $.extend({
    canvas_id: 'hp_canvas',
    svg_id: 'hp_svg',
    appendTo: $('body'),
    hidden: true,
    unit: 'px' // TODO "mm"
  }, o);

  var hp = this;

  this._width = w, this._height = h, this._unit = o.unit;
  this.$wrapper = $('<div/>').addClass('hybridprint wrapper');

  // canvas
  if(o.canvas_id) {
    this.$canvas = $('<canvas/>').attr({
      id: o.canvas_id,
      width: w,
      height: h
    }), this.$canvas.appendTo(this.wrapper());
    this._canvo = this.$canvas.canvo();
  }

  // svg
  if(o.svg_id) {
    this._svg = new Svg({
      id: o.svg_id,
      width: w,
      height: h
    }), this._svg.appendTo(this.wrapper());
  }

  // iframe for printing
  var $ifr = this.$iframe = $('<iframe/>').css('border', 'none');
  var $dfd = this.$dfd = new $.Deferred();

  var $div = this.$div = $('<div/>');
  if(o.hidden === true) {
    $div.css({
      opacity: 0
    });
  } else {
    $ifr.attr({
      width: this._width,
      height: this._height
    });
  }
  $div.appendTo(o.appendTo).append(this.$iframe);

  $ifr.ready(function() {
    var win = $ifr.get(0).contentWindow, doc = win.document;
    var sty = '@page {';
    sty += 'size: ';
    sty += (o.size ? o.size: hp._width + hp.unit + ' ' + hp._height + hp.unit)
      + ';';
    sty += 'margin: ';
    sty += '0;';
    sty += '}';
    doc.body.style.margin = 0;
    $(doc.head).append($('<style type="text/css" media="print"/>').text(sty));
    $(doc.body).append(hp.wrapper());
    $dfd.resolve(), $dfd = null;
  });

};

(function() {

  var HybridProtos = {
    wrapper: wrapper
  };
  for( var i in HybridProtos)
    HybridPrint.prototype[i] = HybridProtos[i];

  var HybridProtosAsync = { // return this.
    line: line,
    rect: rect,
    circle: circle,
    ellipse: ellipse,
    text: text,
    image: image,
    print: print,
    remove: remove
  };
  for( var i in HybridProtosAsync)
    HybridPrint.prototype[i] = (function(i) {
      return function() {
        var hp = this, args = arguments;
        $.when(hp.$dfd).done(function() {
          HybridProtosAsync[i].apply(hp, args);
        });
        return hp;
      };
    })(i);

  function wrapper() {
    return this.$wrapper;
  }

  function line(x1, y1, x2, y2, o) {
    o = setCapitalizedKey($.extend({
      x1: x1,
      y1: y1,
      x2: x2,
      y2: y2,
      border: '1px solid #444'
    }, o));
    adoptBorder(o);

    var w = o.x2 === null ? o.x1: Math.abs(o.x1 - o.x2);
    o = calcAlign(this, w, ['x1', 'x2'], o);
    this._svg.line(o);
  }

  function rect(x, y, w, h, o) {
    o = setCapitalizedKey($.extend({
      x: x,
      y: y,
      width: w,
      height: h,
      border: '1px solid #444',
      background: 'transparent'
    }, o));
    adoptBorder(o);
    adoptBackground(o);

    if(isNaN(parseInt(o.x)) && !o.align)
      o.align = o.x;
    o = calcAlign(this, o.width, ['x', 'w'], o);
    this._svg.rect(o);
  };

  function circle(cx, cy, r, o) {
    o = setCapitalizedKey($.extend({
      cx: cx,
      cy: cy,
      r: r,
      border: '1px solid #444',
      background: 'transparent'
    }, o));
    adoptBorder(o);
    adoptBackground(o);

    o = calcAlign(this, parseInt(o.r) * 2 || o.r, ['cx', 'r'], o);
    this._svg.circle(o);
  }

  function ellipse(cx, cy, rx, ry, o) {
    o = setCapitalizedKey($.extend({
      cx: cx,
      cy: cy,
      rx: rx,
      ry: ry,
      border: '1px solid #444',
      background: 'transparent'
    }, o));
    adoptBorder(o);
    adoptBackground(o);

    o = calcAlign(this, parseInt(o.rx) * 2 || o.rx, ['cx', 'rx'], o);
    this._svg.ellipse(o);
  }

  function text(t, o) {
    o = setCapitalizedKey($.extend({
      x: 0,
      y: 0,
      color: '#444',
      'font-size': '10.5px',
      'font-family': 'serif'
    }, o));
    adoptColor(o);

    var item = this._svg.text(t, o);

    // chrome's getComputedTextLength is not correct when letter-spacing is set.
    var w = item.getComputedTextLength(), c = item.getNumberOfChars();
    var ls = parseInt(o['letter-spacing']) || 0;

    calcAlign(this, w + (c - 1) * ls, true, o, item);
  }

  function image(href, o) {
    o = setCapitalizedKey($.extend({
      x: 0,
      y: 0,
      width: '100px',
      height: '100px',
    }, o));

    var iw = o['image-width'] || o.width;
    if(iw && /%/.test(o.width))
      iw = iw * (parseFloat(o.width) / 100);
    if(!iw)
      throw new Error('image-width must be set for: ' + href);

    o = calcAlign(this, iw, ['x', 'w'], o);
    this._svg.image(href, o);
  }

  function setCapitalizedKey(o) {
    $.each(o, function(k, v) {
      if(/([A-Z])/.test(k))
        o[k.replace(RegExp.$1, '-' + RegExp.$1.toLowerCase())] = v;
    });
    return o;
  }

  function errAnalyzingFailure(type) {
    return type + ' analyzing failure: ';
  }

  function adoptColor(o) {
    var rgb = null, alp = null, pre = null;
    try {
      rgb = codeToRgb(o.color).join();
      alp = o.alpha, pre = alp ? 'rgba': 'rgb';
    } catch(e) {
      console.warn(errAnalyzingFailure('Color') + o.color);
      console.warn(e);
    };
    if(!o.fill)
      o.fill = pre ? pre + "(" + rgb + (alp ? ',' + alp: '') + ")": o.color;
  }

  function adoptBackground(o) {
    var rgb = null, alp = null, pre = null;

    try {
      if(!/transparent/.test(o.background)) {
        rgb = codeToRgb(o.background).join();
        alp = o.alpha, pre = alp ? 'rgba': 'rgb';
      }
    } catch(e) {
      console.warn(errAnalyzingFailure('Background') + o.background);
      console.warn(e);
    };
    if(!o.fill)
      o.fill = pre ? pre + "(" + rgb + (alp ? ',' + alp: '') + ")"
        : o.background;
  }

  function adoptBorder(o) {
    var bdr = null, rgb = null, alp = null, pre = null;
    try {
      bdr = o.border.split(/\s/), rgb = codeToRgb(bdr[2]).join();
      alp = o.alpha, pre = alp ? 'rgba': 'rgb';
    } catch(e) {
      console.warn(errAnalyzingFailure('Border') + o.border);
      console.warn(e);
    }
    if(!o.stroke)
      o.stroke = pre ? pre + "(" + rgb + (alp ? ',' + alp: '') + ")": bdr[2];
    if(!o['stroke-width'])
      o['stroke-width'] = String(bdr[0]).replace(/px/, '');
  }

  function calcAlign(hp, w, keys, o, item) {

    var margin = null, align = null, left = null;

    o = $.extend({}, o);

    var left_key = 'x';
    if($.isArray(keys)) {
      if(keys.indexOf('x1') != -1)
        left_key = 'x1';
      else if(keys.indexOf('cx') != -1)
        left_key = 'cx';
    };

    if(o.align)
      align = o.align;
    else if(isNaN(parseInt(o[left_key])))
      align = o[left_key], o[left_key] = 0;

    if(!align)
      return o;

    margin = o.margin;
    if(!$.isArray(margin))
      switch(align) {
      case 'center':
        margin = [o.margin, o.margin];
        break;
      case 'right':
        margin = [null, o.margin];
        break;
      }

    margin.forEach(function(v, i) {
      margin[i] = parseInt(margin[i]) ? parseInt(margin[i]): 0;
    });

    switch(align) {
    case 'center':
      if(w === 'auto')
        w = hp._width - margin[0] - margin[1];
      left = margin[0] + (hp._width - margin[0] - margin[1] - w) / 2;
      break;
    case 'right':
      left = margin[0] + (hp._width - margin[0] - margin[1] - w);
      break;
    default:
      left = margin[0];
    }

    var fn = item ? function(k, v) {
      item.setAttribute(k, v);
    }: function(k, v) {
      o[k] = v;
    };

    if(keys == true)
      fn('x', left);
    else
      keys.forEach(function(k) {
        if(k == 'x')
          return fn('x', left);
        if(k == 'x1')
          return fn('x1', left);
        if(k == 'x2')
          return fn('x2', left + w);
        if(k == 'cx')
          return fn('cx', left + w / 2);
        if(k == 'w')
          return fn('width', w);
        if(k == 'r' || k == 'rx')
          return fn(k, w / 2);
      });

    return o;

  }

  function print() {
    if(this.$iframe)
      this.$iframe.get(0).contentWindow.print();
    if(this.$div.parent().is('body'))
      this.$div.remove();
  }

  function remove() {
    this.$div.remove();
  }

  // utilities >>
  function codeToRgb(code) {
    var ccode = codeAdjust(code).replace(/^#/, '');
    return [parseInt(ccode.slice(0, 2), '16'),
      parseInt(ccode.slice(2, 4), '16'), parseInt(ccode.slice(4, 6), '16')];
  }

  function codeAdjust(code) {
    if(code.substr(0, 3) == 'rgb')
      return code.replace(/-/g, ',');
    if(!(code.charAt(0) == '#' && (code.length == 4 || code.length == 7)))
      throw new Error([' - illegal color code.(code = ', code, ')'].join(""));
    if(code.length == 4)
      code = [code[0], code[1], code[1], code[2], code[2], code[3], code[3]]
          .join("");
    return code;
  }

})();
<|endoftext|>


<commit_before>module.exports = function() {
  const fs = require('fs');
  const request = require('request');
  const getJson = require('./getjson.js');
  const clientid = require('./clientid.js');

  const americas = require('./public/americas.json');
  const china = require('./public/china.json');
  const europe = require('./public/europe.json');
  const se_asia = require('./public/se_asia.json');

  // twitch api login
  const login = {
    url: 'https://api.twitch.tv/kraken/streams?limit=100&offset=0&game=DOTA+2',
    headers: {
      "Client-ID": clientid.clientId
    }
  };

  class Streamer {
    constructor(name, rank, region, url, img, lang, card) {
      this.name = name;
      this.rank = rank;
      this.region = region;
      this.url = url;
      this.img = img;
      this.lang = lang;
      this.card = card;
    }
  }

  let streamers = []; // list of top tier players

  function getRegion(region, regionName) {
    for (let i=0; i < region.leaderboard.length; i++) {
      let streamer = new Streamer(region.leaderboard[i].name, i+1, regionName);
      streamers.push(streamer);
      }
    }

  getRegion(americas, 'Americas');
  getRegion(china, 'China');
  getRegion(europe, 'Europe');
  getRegion(se_asia, 'Southeast Asia');

  let playerMap = new Map(); // player map where the value is the index of the players

  for (let i=0; i < streamers.length; i++) {
    playerMap.set(streamers[i].name, i);
  }

  let filteredPlayers = []; // when the streamer list is reduced it is pushed to this array
  let twitch = [];  // list from Twitch JSON request
  let cards = '';

  // Twitch API call
  request(login, function(error, response, body) {
    function filterList(arr) {
      for (let i=0; i < arr.length; i++) {
        if (playerMap.has(arr[i].name) === true) {
          streamers[playerMap.get(arr[i].name)].url = arr[i].url;
          streamers[playerMap.get(arr[i].name)].img = arr[i].img;
          streamers[playerMap.get(arr[i].name)].lang = arr[i].lang;
        }
      }
      reduceList(streamers);
      for (let p in filteredPlayers) {
        if (filteredPlayers[p].rank === undefined) {
          filteredPlayers[p].rank = 0;
        }
        filteredPlayers[p].card = `

${filteredPlayers[p].name}

                                        Rank ${filteredPlayers[p].rank}

                                        Region: ${filteredPlayers[p].region}

                                  \n`;
      }
      filteredPlayers.sort(function(a, b) {
        return (a.rank) - (b.rank);
      });
      fs.writeFile('./public/dreamstream.json', JSON.stringify(filteredPlayers), 'UTF-8', (err) => {
        if (err) throw err;
      });
      for (let c in filteredPlayers) {
        cards = cards + filteredPlayers[c].card;
      }
      let cardsJson = { text: cards };

      fs.writeFile('./public/cards.json', JSON.stringify(cardsJson), 'UTF-8', (err) => {
        if (err) throw err;
      });
    }
  // says if there is no twitch url then don't bother including it on the list
    function reduceList(arr) {
      for (let i=0; i < arr.length; i++) {
        if (arr[i].url !== undefined) {
          filteredPlayers.push(arr[i]);
        }
      }
    }

    if (!error && response.statusCode == 200) {
      let live = JSON.parse(body);
      for (let i=0; i < live.streams.length; i++) {
        let stream = new Streamer(live.streams[i].channel.display_name, null, null, live.streams[i].channel.url, live.streams[i].channel.logo, live.streams[i].channel.broadcaster_language);
        twitch.push(stream);
      }
      nameSwitch();
      filterList(twitch);
    } else {
      console.log('Error: ' + error + ' Status code: ' + response.statusCode);
    }
  });

  // on left: twitch name, on right: valve name
  function nameSwitch() {
    for (let i=0; i < twitch.length; i++) {
      let name = twitch[i].name;
      switch(name) {
        case "0Timado0": twitch[i].name = "Timado";
        break;
        case "33dota": twitch[i].name = "33";
        break;
        case "7ckngMad": twitch[i].name = "7Mad-";
        break;
        case "ABFnggshka": twitch[i].name = "Fng";
        break;
        case "ALOHADANCETV": twitch[i].name = "ALOHADANCE";
        break;
        case "Attackerdota": twitch[i].name = "!Attacker";
        break;
        case "Arteezy": twitch[i].name = "rtz";
        break;
        case "BananaSlamJamma": twitch[i].name = "BSJ";
        break;
        case "BigDaddy": twitch[i].name = "BigDaddyN0tail";
        break;
        case "BlackDotATV": twitch[i].name = "Black^";
        break;
        case "BlitzDotA": twitch[i].name = "Blitz";
        break;
        case "BloodyNine": twitch[i].name = "Bloody Nine";
        break;
        case "bryle_": twitch[i].name = "Bryle";
        break;
        case "canceldota": twitch[i].name = "canceL^^";
        break;
        case "CCnCDotA2": twitch[i].name = "CCnC";
        break;
        case "Cr1tdota": twitch[i].name = "Cr1t-";
        break;
        case "Dota2FATA": twitch[i].name = "Fata";
        break;
        case "dotademon": twitch[i].name = "DeMoN";
        break;
        case "DotACapitalist": twitch[i].name = "Capitalist";
        break;
        case "Eosintrash": twitch[i].name = "Eosin";
        break;
        case "EternaLEnVyy": twitch[i].name = "EternaLEnVy";
        break;
        case "FearDarkness": twitch[i].name = "Fear";
        break;
        case "febbydoto": twitch[i].name = "Febby";
        break;
        case "forev": twitch[i].name = "FoREv";
        break;
        case "fozzy4444": twitch[i].name = "tv/fozzy4444";
        break;
        case "GGwpLanaya": twitch[i].name = "GGwpLanaya Ift";
        break;
        case "Gorgcc": twitch[i].name = "Gorgc";
        break;
        case "illidanstr": twitch[i].name = "Illidan Stormrage SF46";
        break;
        case "inK_Dota": twitch[i].name = "@inKDota";
        break;
        case "k13sz": twitch[i].name = "twitch.tv/k13sz";
        break;
        case "lanarinho": twitch[i].name = "Larano";
        break;
        case "lizZardDota2": twitch[i].name = "lizzard";
        break;
        case "MatthewDota": twitch[i].name = "Matthew~";
        break;
        case "midone": twitch[i].name = "MidOne";
        break;
        case "Miracle_doto": twitch[i].name = "Miracle-";
        break;
        case "MiSeRyTheSLAYER": twitch[i].name = "MiSeRy";
        break;
        case "MooDota2": twitch[i].name = "Moo";
        break;
        case "Moonmeander": twitch[i].name = "MoonMayMays";
        break;
        case "nooneboss": twitch[i].name = "No[o]ne-";
        break;
        case "PurgeGamers": twitch[i].name = "Purge";
        break;
        case "peterpandam": twitch[i].name = "Peterpandam";
        break;
        case "ramzesdoto": twitch[i].name = "RAMZES666";
        break;
        case "resolut1ontv": twitch[i].name = "Resolut1on";
        break;
        case "shuma4": twitch[i].name = "ShuMa";
        break;
        case "Sing_sing": twitch[i].name = "SingSing";
        break;
        case "slahserDota": twitch[i].name = "slahser";
        break;
        case "smashdota": twitch[i].name = "SmAsH";
        break;
        case "SneykingDota": twitch[i].name = "Sneyking";
        break;
        case "SumaiLDoto": twitch[i].name = "SumaiL";
        break;
        case "Sovereigndota": twitch[i].name = "Sovereign";
        break;
        case "topsonous": twitch[i].name = "Topson";
        break;
        case "universedota": twitch[i].name = "Universe";
        break;
        case "vanNDota": twitch[i].name = "vanN";
        break;
        case "w33haa": twitch[i].name = "w33";
        break;
        case "WagamamaTV": twitch[i].name = "Wagamama";
        break;
        case "YapzOrdota": twitch[i].name = "YapzOr";
        break;
        case "y0nd.Alina": twitch[i].name = "y0nd";
        break;
      }
    }
  }
}
<commit_msg>Changed how players are added to the playerMap<commit_after>module.exports = function() {
  const fs = require('fs');
  const request = require('request');
  const getJson = require('./getjson.js');
  const clientid = require('./clientid.js');

  const americas = require('./public/americas.json');
  const china = require('./public/china.json');
  const europe = require('./public/europe.json');
  const se_asia = require('./public/se_asia.json');

  // twitch api login
  const login = {
    url: 'https://api.twitch.tv/kraken/streams?limit=100&offset=0&game=DOTA+2',
    headers: {
      "Client-ID": clientid.clientId
    }
  };

  class Streamer {
    constructor(name, rank, region, url, img, lang, card) {
      this.name = name;
      this.rank = rank;
      this.region = region;
      this.url = url;
      this.img = img;
      this.lang = lang;
      this.card = card;
    }
  }

  let streamers = []; // list of top tier players

  function getRegion(region, regionName) {
    for (let i=0; i < region.leaderboard.length; i++) {
      let streamer = new Streamer(region.leaderboard[i].name, i+1, regionName);
      streamers.push(streamer);
      }
    }

  getRegion(americas, 'Americas');
  getRegion(china, 'China');
  getRegion(europe, 'Europe');
  getRegion(se_asia, 'Southeast Asia');

  let playerMap = new Map(); // player map where the value is the index of the players

  for (let i=0; i < streamers.length; i++) {
    if (playerMap.has(streamers[i].name) === false) {
      playerMap.set(streamers[i].name, i);
    }
  }

  let filteredPlayers = []; // when the streamer list is reduced it is pushed to this array
  let twitch = [];  // list from Twitch JSON request
  let cards = '';

  // Twitch API call
  request(login, function(error, response, body) {
    function filterList(arr) {
      for (let i=0; i < arr.length; i++) {
        if (playerMap.has(arr[i].name) === true) {
          streamers[playerMap.get(arr[i].name)].url = arr[i].url;
          streamers[playerMap.get(arr[i].name)].img = arr[i].img;
          streamers[playerMap.get(arr[i].name)].lang = arr[i].lang;
        }
      }
      reduceList(streamers);
      for (let p in filteredPlayers) {
        if (filteredPlayers[p].rank === undefined) {
          filteredPlayers[p].rank = 0;
        }
        filteredPlayers[p].card = `

${filteredPlayers[p].name}

                                        Rank ${filteredPlayers[p].rank}

                                        Region: ${filteredPlayers[p].region}

                                  \n`;
      }
      filteredPlayers.sort(function(a, b) {
        return (a.rank) - (b.rank);
      });
      fs.writeFile('./public/dreamstream.json', JSON.stringify(filteredPlayers), 'UTF-8', (err) => {
        if (err) throw err;
      });
      for (let c in filteredPlayers) {
        cards = cards + filteredPlayers[c].card;
      }
      let cardsJson = { text: cards };

      fs.writeFile('./public/cards.json', JSON.stringify(cardsJson), 'UTF-8', (err) => {
        if (err) throw err;
      });
    }
  // says if there is no twitch url then don't bother including it on the list
    function reduceList(arr) {
      for (let i=0; i < arr.length; i++) {
        if (arr[i].url !== undefined) {
          filteredPlayers.push(arr[i]);
        }
      }
    }

    if (!error && response.statusCode == 200) {
      let live = JSON.parse(body);
      for (let i=0; i < live.streams.length; i++) {
        let stream = new Streamer(live.streams[i].channel.display_name, null, null, live.streams[i].channel.url, live.streams[i].channel.logo, live.streams[i].channel.broadcaster_language);
        twitch.push(stream);
      }
      nameSwitch();
      filterList(twitch);
    } else {
      console.log('Error: ' + error + ' Status code: ' + response.statusCode);
    }
  });

  // on left: twitch name, on right: valve name
  function nameSwitch() {
    for (let i=0; i < twitch.length; i++) {
      let name = twitch[i].name;
      switch(name) {
        case "0Timado0": twitch[i].name = "Timado";
        break;
        case "33dota": twitch[i].name = "33";
        break;
        case "7ckngMad": twitch[i].name = "7Mad-";
        break;
        case "ABFnggshka": twitch[i].name = "Fng";
        break;
        case "ALOHADANCETV": twitch[i].name = "ALOHADANCE";
        break;
        case "Attackerdota": twitch[i].name = "!Attacker";
        break;
        case "Arteezy": twitch[i].name = "rtz";
        break;
        case "BananaSlamJamma": twitch[i].name = "BSJ";
        break;
        case "BigDaddy": twitch[i].name = "BigDaddyN0tail";
        break;
        case "BlackDotATV": twitch[i].name = "Black^";
        break;
        case "BlitzDotA": twitch[i].name = "Blitz";
        break;
        case "BloodyNine": twitch[i].name = "Bloody Nine";
        break;
        case "bryle_": twitch[i].name = "Bryle";
        break;
        case "canceldota": twitch[i].name = "canceL^^";
        break;
        case "CCnCDotA2": twitch[i].name = "CCnC";
        break;
        case "Cr1tdota": twitch[i].name = "Cr1t-";
        break;
        case "Dota2FATA": twitch[i].name = "Fata";
        break;
        case "dotademon": twitch[i].name = "DeMoN";
        break;
        case "DotACapitalist": twitch[i].name = "Capitalist";
        break;
        case "Eosintrash": twitch[i].name = "Eosin";
        break;
        case "EternaLEnVyy": twitch[i].name = "EternaLEnVy";
        break;
        case "FearDarkness": twitch[i].name = "Fear";
        break;
        case "febbydoto": twitch[i].name = "Febby";
        break;
        case "forev": twitch[i].name = "FoREv";
        break;
        case "fozzy4444": twitch[i].name = "tv/fozzy4444";
        break;
        case "GGwpLanaya": twitch[i].name = "GGwpLanaya Ift";
        break;
        case "Gorgcc": twitch[i].name = "Gorgc";
        break;
        case "illidanstr": twitch[i].name = "Illidan Stormrage SF46";
        break;
        case "inK_Dota": twitch[i].name = "@inKDota";
        break;
        case "k13sz": twitch[i].name = "twitch.tv/k13sz";
        break;
        case "lanarinho": twitch[i].name = "Larano";
        break;
        case "lizZardDota2": twitch[i].name = "lizzard";
        break;
        case "MatthewDota": twitch[i].name = "Matthew~";
        break;
        case "midone": twitch[i].name = "MidOne";
        break;
        case "Miracle_doto": twitch[i].name = "Miracle-";
        break;
        case "MiSeRyTheSLAYER": twitch[i].name = "MiSeRy";
        break;
        case "MooDota2": twitch[i].name = "Moo";
        break;
        case "Moonmeander": twitch[i].name = "MoonMayMays";
        break;
        case "nooneboss": twitch[i].name = "No[o]ne-";
        break;
        case "PurgeGamers": twitch[i].name = "Purge";
        break;
        case "peterpandam": twitch[i].name = "Peterpandam";
        break;
        case "ramzesdoto": twitch[i].name = "RAMZES666";
        break;
        case "resolut1ontv": twitch[i].name = "Resolut1on";
        break;
        case "shuma4": twitch[i].name = "ShuMa";
        break;
        case "Sing_sing": twitch[i].name = "SingSing";
        break;
        case "slahserDota": twitch[i].name = "slahser";
        break;
        case "smashdota": twitch[i].name = "SmAsH";
        break;
        case "SneykingDota": twitch[i].name = "Sneyking";
        break;
        case "SumaiLDoto": twitch[i].name = "SumaiL";
        break;
        case "Sovereigndota": twitch[i].name = "Sovereign";
        break;
        case "topsonous": twitch[i].name = "Topson";
        break;
        case "universedota": twitch[i].name = "Universe";
        break;
        case "vanNDota": twitch[i].name = "vanN";
        break;
        case "w33haa": twitch[i].name = "w33";
        break;
        case "WagamamaTV": twitch[i].name = "Wagamama";
        break;
        case "YapzOrdota": twitch[i].name = "YapzOr";
        break;
        case "y0nd.Alina": twitch[i].name = "y0nd";
        break;
      }
    }
  }
}
<|endoftext|>


<commit_before>/**
 * jQuery.contextMenu - Show a custom context when right clicking something
 * Jonas Arnklint, http://github.com/arnklint/jquery-contextMenu
 * Released into the public domain
 * Date: Oct 7, 2010
 * @author Jonas Arnklint
 * @version 1.2
 *
 */
jQuery.fn.contextMenu = function ( name, actions, options ) {

    var me = this,
        menu = $('

').hide().appendTo('body'),
        active_element = null, // last clicked element that responds with contextMenu
        hide_menu = function(){
            $('.context-menu').hide()
        },
        default_options = {
            disable_native_context_menu: false // disables the native contextmenu everywhere you click
        },
        options = $.extend(default_options, options);

    $(document).bind('contextmenu', function(e) {
      if (options.disable_native_context_menu)
        e.preventDefault();
      hide_menu();
    });

    $.each(actions, function(me, item_options) {
        var menuItem = $('
'+me+'
');

        if (item_options.klass)
          menuItem.attr("class", item_options.klass);

        menuItem.appendTo(menu).bind('click', function(e) {
            item_options.click(active_element);
            e.preventDefault();
        });
    });

    $('body').click(function() {
         hide_menu(); //Hide the menus if visible
    });

    return me.bind('contextmenu', function(e){
        active_element = $(this); // set clicked element
        hide_menu();
        menu.show()
            .css({
                position: 'absolute',
                top: e.pageY,
                left: e.pageX,
                zIndex: 1000
            });
        return false;
    });
}
<commit_msg>o Wrapping in a local '$' alias to support jQuery.noConflict<commit_after>/**
 * jQuery.contextMenu - Show a custom context when right clicking something
 * Jonas Arnklint, http://github.com/arnklint/jquery-contextMenu
 * Released into the public domain
 * Date: Jan 14, 2011
 * @author Jonas Arnklint
 * @version 1.2
 *
 */

// Making a local '$' alias of jQuery to support jQuery.noConflict
(function($) {
  jQuery.fn.contextMenu = function ( name, actions, options ) {
      var me = this,
          menu = $('

').hide().appendTo('body'),
          active_element = null, // last clicked element that responds with contextMenu
          hide_menu = function(){
              $('.context-menu').hide()
          },
          default_options = {
              disable_native_context_menu: false // disables the native contextmenu everywhere you click
          },
          options = $.extend(default_options, options);

      $(document).bind('contextmenu', function(e) {
        if (options.disable_native_context_menu)
          e.preventDefault();
        hide_menu();
      });

      $.each(actions, function(me, item_options) {
          var menuItem = $('
'+me+'
');

          if (item_options.klass)
            menuItem.attr("class", item_options.klass);

          menuItem.appendTo(menu).bind('click', function(e) {
              item_options.click(active_element);
              e.preventDefault();
          });
      });

      $('body').click(function() {
           hide_menu(); //Hide the menus if visible
      });

      return me.bind('contextmenu', function(e){
          active_element = $(this); // set clicked element
          hide_menu();
          menu.show()
              .css({
                  position: 'absolute',
                  top: e.pageY,
                  left: e.pageX,
                  zIndex: 1000
              });
          return false;
      });
  }
})(jQuery);
<|endoftext|>


<commit_before>/*
Project Name: Fancy Forms
URL: https://github.com/keobrien/Fancy-Forms
Author: Kevin O'Brien
Company: Clockwork Acive Media Systems
Company Site: clockwork.net
License: MIT
Copyright (C) 2012 Clockwork Active Media Systems
Version: 0.1
**************************************/

(function ($) {

	"use strict";

	// These locally scoped variables help minification by aliasing strings
	var data_key               =  'CW_fancy_forms',
		event_suffix           =  '.CW_fancy_forms',
	// Custom events
		component_initialized  =  'component_initialized' + event_suffix,
		component_error        =  'component_error'       + event_suffix,
		event_change           =  'fancy_change'          + event_suffix;

	var methods  =  {

		/* Selects
		*****************/
		_init_selects  :  function (settings) {

			if($(this).hasClass('fancy_selects-active')) { return this; }

			var $el  =  $(this),
				options  =  $.extend({
					content         :  null,
					selected        :  $el.find('option:selected'),
					wrap_class      :  'fancy_selects-wrap',
					wrap_id         :  $el.attr('id') ? 'fancy_selects-' + $el.attr('id') : '',
					wrap_tag        :  'div',
					visible_class   :  'fancy_selects-visible',
					visible_tag     :  'div'
				}, settings);

			var visible_content  =  options.content || options.selected.html();
			options.wrap_html       =  '<' + options.wrap_tag + ' class="' + options.wrap_class + '" id="' + options.wrap_id + '"></' + options.wrap_tag + '>';
			options.visible_html   =  '<' + options.visible_tag + ' class="' + options.visible_class + '">' + visible_content + '</' + options.visible_tag + '>';

			$el.data(data_key, options);

			methods._make_fancy_select($el);

			return this;
		},

		_make_fancy_select  :  function ($el) {

			var	options  =  $el.data(data_key);

			$el.wrap(options.wrap_html).addClass('fancy_selects-active');

			options.$wrap     =  $el.parent();
			options.$visible  =  $(options.visible_html).appendTo(options.$wrap);
			if ($.browser.msie  && parseInt($.browser.version, 10) < 8) {
				$('
ν
').appendTo(options.$wrap);
			}

			methods.apply_facy_css($el, options.$wrap);

			$el.change(methods.update_selected_select);

			$el.trigger(component_initialized, options);
		},

		update_selected_select  :  function (evt) {

			var	$el      =  $(evt.currentTarget),
				options  =  $el.data(data_key);

			options.selected  =  options.$wrap.find('option:selected');
			options.$visible.html(options.selected.html());

			$el.trigger(event_change, options);
		},

		/* Shared
		*****************/
		apply_facy_css  :  function($el, $wrapper) {

			$wrapper
				.css({
					'position'       :  'relative',
					'width'          :  $el.outerWidth() + 'px'
				})
				.addClass($el.attr('class'))
				.attr('id', data_key + '-' + $el.attr('id' ));

			$el.css({
				'opacity'  :  0,
				'min-height'  :  '100%',
				'min-width'   :  '100%',
				'position'    :  'absolute',
				'top'         :  0,
				'left'        :  0,
				'z-index'     :  2,
				'cursor'      :  'pointer'
			});
		},

		/* Checkboxes
		*****************/
		_init_checks  :  function (settings) {

			var $el  =  $(this),
				options  =  $.extend({
					selected_class  :  'fancy_checkbox-checked',
					wrap_class      :  'fancy_checkbox-wrap',
					wrap_id         :  $el.attr('id') ? 'fancy_checkbox-' + $el.attr('id') : '',
					wrap_tag        :  'div'
				}, settings);

			options.wrap_html       =  '<' + options.wrap_tag + ' class="' + options.wrap_class + '" id="' + options.wrap_id + '"></' + options.wrap_tag + '>';

			$el.data(data_key, options);

			methods._make_fancy_checks($el);

			return this;
		},

		_make_fancy_checks  :  function ($el) {

			var	options  =  $el.data(data_key);

			$el
				.wrap(options.wrap_html)
				.change(methods.update_selected_check)
				.each(methods.update_selected_check)
				.trigger(component_initialized, options);

			methods.apply_facy_css($el, $el.parent());
		},

		update_selected_check  :  function (evt) {

			var	options  =  evt ? $(evt.currentTarget).data(data_key) : $(this).data(data_key),
				$el   =  $(this),
				checked  =  $el.attr('checked');

			if(checked === 'checked') {
				$el.parent().addClass(options.selected_class);
			}else {
				$el.parent().removeClass(options.selected_class);
			}

			$el.trigger(event_change, options);
		}
	};

	$.fn.cw_fancy_selects  =  function (method) {

		if (methods[method] && method.charAt(0) !== '_') {
			return $(this).map(function(i, val) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); });
		} else if (typeof method === 'object' || !method) {
			var args  =  arguments;
			return $(this).map(function(i, val) { return methods._init_selects.apply(this, args); });
		}
	};

	$.fn.cw_fancy_checks  =  function (method) {

		if (methods[method] && method.charAt(0) !== '_') {
			return $(this).map(function(i, val) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); });
		} else if (typeof method === 'object' || !method) {
			var args  =  arguments;
			return $(this).map(function(i, val) { return methods._init_checks.apply(this, args); });
		}
	};

}(jQuery));<commit_msg>spelling<commit_after>/*
Project Name: Fancy Forms
URL: https://github.com/keobrien/Fancy-Forms
Author: Kevin O'Brien
Company: Clockwork Acive Media Systems
Company Site: clockwork.net
License: MIT
Copyright (C) 2012 Clockwork Active Media Systems
Version: 0.1
**************************************/

(function ($) {

	"use strict";

	// These locally scoped variables help minification by aliasing strings
	var data_key               =  'CW_fancy_forms',
		event_suffix           =  '.CW_fancy_forms',
	// Custom events
		component_initialized  =  'component_initialized' + event_suffix,
		component_error        =  'component_error'       + event_suffix,
		event_change           =  'fancy_change'          + event_suffix;

	var methods  =  {

		/* Selects
		*****************/
		_init_selects  :  function (settings) {

			if($(this).hasClass('fancy_selects-active')) { return this; }

			var $el  =  $(this),
				options  =  $.extend({
					content         :  null,
					selected        :  $el.find('option:selected'),
					wrap_class      :  'fancy_selects-wrap',
					// consider a private function
					wrap_id         :  $el.attr('id') ? 'fancy_selects-' + $el.attr('id') : '',
					wrap_tag        :  'div',
					visible_class   :  'fancy_selects-visible',
					visible_tag     :  'div'
				}, settings);

			var visible_content  =  options.content || options.selected.html();
			options.wrap_html       =  '<' + options.wrap_tag + ' class="' + options.wrap_class + '" id="' + options.wrap_id + '"></' + options.wrap_tag + '>';
			options.visible_html   =  '<' + options.visible_tag + ' class="' + options.visible_class + '">' + visible_content + '</' + options.visible_tag + '>';

			$el.data(data_key, options);

			methods._make_fancy_select($el);

			return this;
		},

		_make_fancy_select  :  function ($el) {

			var	options  =  $el.data(data_key);

			$el.wrap(options.wrap_html).addClass('fancy_selects-active');

			options.$wrap     =  $el.parent();
			options.$visible  =  $(options.visible_html).appendTo(options.$wrap);
			if ($.browser.msie  && parseInt($.browser.version, 10) < 8) {
				$('
ν
').appendTo(options.$wrap);
			}

			methods.apply_fancy_css($el, options.$wrap);

			$el
				.change(methods.update_selected_select)
				.on(event_change, $wrap, methods.update_selected_select);

			$el.trigger(component_initialized, $wrap, options);
		},

		update_selected_select  :  function (evt) {

			var	$el      =  $(evt.currentTarget),
				options  =  $el.data(data_key);

			options.selected  =  options.$wrap.find('option:selected');
			options.$visible.html(options.selected.html());

			$el.trigger(event_change, options);
		},

		/* Shared
		*****************/
		apply_fancy_css  :  function($el, $wrapper) {

			$wrapper
				.css({
					'position'       :  'relative',
					'width'          :  $el.outerWidth() + 'px'
				})
				.addClass($el.attr('class'))
				.attr('id', data_key + '-' + $el.attr('id' ));

			$el.css({
				'opacity'  :  0,
				'min-height'  :  '100%',
				'min-width'   :  '100%',
				'position'    :  'absolute',
				'top'         :  0,
				'left'        :  0,
				'z-index'     :  2,
				'cursor'      :  'pointer'
			});
		},

		/* Checkboxes
		*****************/
		_init_checks  :  function (settings) {

			var $el  =  $(this),
				options  =  $.extend({
					selected_class  :  'fancy_checkbox-checked',
					wrap_class      :  'fancy_checkbox-wrap',
					wrap_id         :  $el.attr('id') ? 'fancy_checkbox-' + $el.attr('id') : '',
					wrap_tag        :  'div'
				}, settings);

			options.wrap_html       =  '<' + options.wrap_tag + ' class="' + options.wrap_class + '" id="' + options.wrap_id + '"></' + options.wrap_tag + '>';

			$el.data(data_key, options);

			methods._make_fancy_checks($el);

			return this;
		},

		_make_fancy_checks  :  function ($el) {

			var	options  =  $el.data(data_key);

			$el
				.wrap(options.wrap_html)
				.change(methods.update_selected_check)
				.each(methods.update_selected_check)
				.trigger(component_initialized, options)
				.on(event_change, $wrap, methods.update_selected_select);

			methods.apply_fancy_css($el, $el.parent());
		},

		update_selected_check  :  function (evt) {

			var	options  =  evt ? $(evt.currentTarget).data(data_key) : $(this).data(data_key),
				$el   =  $(this),
				checked  =  $el.attr('checked');

			if(checked === 'checked') {
				$el.parent().addClass(options.selected_class);
			}else {
				$el.parent().removeClass(options.selected_class);
			}

			$el.trigger(event_change, options);
		}
	};

	$.fn.cw_fancy_selects  =  function (method) {

		if (methods[method] && method.charAt(0) !== '_') {
			return $(this).map(function(i, val) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); });
		} else if (typeof method === 'object' || !method) {
			var args  =  arguments;
			return $(this).map(function(i, val) { return methods._init_selects.apply(this, args); });
		}
	};

	$.fn.cw_fancy_checks  =  function (method) {

		if (methods[method] && method.charAt(0) !== '_') {
			return $(this).map(function(i, val) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); });
		} else if (typeof method === 'object' || !method) {
			var args  =  arguments;
			return $(this).map(function(i, val) { return methods._init_checks.apply(this, args); });
		}
	};

}(jQuery));<|endoftext|>