<commit_before>/**
 * Copyright (c) 2015-present, Pavel Aksonov
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */
import React, {Component, Animated, StyleSheet, ScrollView, View, Text, NavigationExperimental} from "react-native";
const {
    AnimatedView: NavigationAnimatedView,
    Card: NavigationCard,
    RootContainer: NavigationRootContainer,
    Header: NavigationHeader,
    } = NavigationExperimental;
import Actions from "./Actions";
import getInitialState from "./State";
import Reducer from "./Reducer";
import TabBar from "./TabBar";
import NavBar from "./NavBar";

export default class DefaultRenderer extends Component {
    constructor(props) {
        super(props);
        this._renderCard = this._renderCard.bind(this);
        this._renderScene = this._renderScene.bind(this);
        this._renderHeader = this._renderHeader.bind(this);
    }

    render() {
        const navigationState = this.props.navigationState;
        if (!navigationState) {
            return null;
        }
        let Component = navigationState.component;
        if (navigationState.tabs && !Component){
            Component = TabBar;
        }
        if (Component) {
            return (
                <View style={[{flex: 1}, navigationState.sceneStyle]}>
                    <Component {...navigationState} navigationState={navigationState} />
                </View>
            )
        }

        const selected = navigationState.children[navigationState.index];
        //return <DefaultRenderer key={selected.key} navigationState={selected}/>

        let applyAnimation = selected.applyAnimation || navigationState.applyAnimation;
        let style = selected.style || navigationState.style;
        let direction = selected.direction || navigationState.direction || "horizontal";

        let optionals = {};
        if (applyAnimation) {
            optionals.applyAnimation = applyAnimation;
        } else {
            let duration = selected.duration;
            if (duration === null || duration === undefined) duration = navigationState.duration;
            if (duration !== null && duration !== undefined) {
                optionals.applyAnimation = function (pos, navState) {
                    Animated.timing(pos, {toValue: navState.index, duration}).start();
                };
            }
        }

        return (
            <NavigationAnimatedView
                navigationState={navigationState}
                style={[styles.animatedView, style]}
                renderOverlay={this._renderHeader}
                direction={direction}
                renderScene={this._renderCard}
                {...optionals}
            />
        );
    }

    _renderHeader(/*NavigationSceneRendererProps*/ props) {
        return <NavBar
                {...props}
                getTitle={state => state.title}
            />;
    }

    _renderCard(/*NavigationSceneRendererProps*/ props) {
        return (
            <NavigationCard
                {...props}
                style={props.scene.navigationState.style}
                key={"card_" + props.scene.navigationState.key}
                direction={props.scene.navigationState.direction || "horizontal"}
                panHandlers={props.scene.navigationState.panHandlers }
                renderScene={this._renderScene}
            />
        );
    }

    _renderScene(/*NavigationSceneRendererProps*/ props) {
        return <DefaultRenderer key={props.scene.navigationState.key} navigationState={props.scene.navigationState}/>
    }

}

const styles = StyleSheet.create({
    animatedView: {
        flex: 1,
        backgroundColor:"transparent"
    },
});

<commit_msg>Provide navigationState to scene's context<commit_after>/**
 * Copyright (c) 2015-present, Pavel Aksonov
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */
import React, {Component, Animated, StyleSheet, ScrollView, View, Text, NavigationExperimental} from "react-native";
const {
    AnimatedView: NavigationAnimatedView,
    Card: NavigationCard,
    RootContainer: NavigationRootContainer,
    Header: NavigationHeader,
    } = NavigationExperimental;
import Actions from "./Actions";
import getInitialState from "./State";
import Reducer from "./Reducer";
import TabBar from "./TabBar";
import NavBar from "./NavBar";

export default class DefaultRenderer extends Component {
    constructor(props) {
        super(props);
        this._renderCard = this._renderCard.bind(this);
        this._renderScene = this._renderScene.bind(this);
        this._renderHeader = this._renderHeader.bind(this);
    }

    getChildContext() {
        return {
            navigationState: this.props.navigationState,
        };
    }

    render() {
        const navigationState = this.props.navigationState;
        if (!navigationState) {
            return null;
        }
        let Component = navigationState.component;
        if (navigationState.tabs && !Component){
            Component = TabBar;
        }
        if (Component) {
            return (
                <View style={[{flex: 1}, navigationState.sceneStyle]}>
                    <Component {...navigationState} navigationState={navigationState} />
                </View>
            )
        }

        const selected = navigationState.children[navigationState.index];
        //return <DefaultRenderer key={selected.key} navigationState={selected}/>

        let applyAnimation = selected.applyAnimation || navigationState.applyAnimation;
        let style = selected.style || navigationState.style;
        let direction = selected.direction || navigationState.direction || "horizontal";

        let optionals = {};
        if (applyAnimation) {
            optionals.applyAnimation = applyAnimation;
        } else {
            let duration = selected.duration;
            if (duration === null || duration === undefined) duration = navigationState.duration;
            if (duration !== null && duration !== undefined) {
                optionals.applyAnimation = function (pos, navState) {
                    Animated.timing(pos, {toValue: navState.index, duration}).start();
                };
            }
        }

        return (
            <NavigationAnimatedView
                navigationState={navigationState}
                style={[styles.animatedView, style]}
                renderOverlay={this._renderHeader}
                direction={direction}
                renderScene={this._renderCard}
                {...optionals}
            />
        );
    }

    _renderHeader(/*NavigationSceneRendererProps*/ props) {
        return <NavBar
                {...props}
                getTitle={state => state.title}
            />;
    }

    _renderCard(/*NavigationSceneRendererProps*/ props) {
        return (
            <NavigationCard
                {...props}
                style={props.scene.navigationState.style}
                key={"card_" + props.scene.navigationState.key}
                direction={props.scene.navigationState.direction || "horizontal"}
                panHandlers={props.scene.navigationState.panHandlers }
                renderScene={this._renderScene}
            />
        );
    }

    _renderScene(/*NavigationSceneRendererProps*/ props) {
        return <DefaultRenderer key={props.scene.navigationState.key} navigationState={props.scene.navigationState}/>
    }

}

DefaultRenderer.childContextTypes = {
    navigationState: PropTypes.any,
};

const styles = StyleSheet.create({
    animatedView: {
        flex: 1,
        backgroundColor:"transparent"
    },
});

<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var util = require('util'),
  Oauth1Strategy = require('../lib/passport-oauth1'); // SPECIAL OAUTH PATCHED TO READ IN A KEY AND SECRET

function Strategy(options, verify) {
  options = options || {};
  options.requestTokenURL = 'https://api-partner.network.xero.com/oauth/RequestToken';
  options.accessTokenURL = 'https://api-partner.network.xero.com/oauth/AccessToken';
  options.userAuthorizationURL = 'https://api.xero.com/oauth/Authorize';

  Oauth1Strategy.call(this, options, verify);

  this.name = 'xero';
}

util.inherits(Strategy, Oauth1Strategy);

module.exports = Strategy;
<commit_msg>xero changed their api endpoints<commit_after>/**
 * Module dependencies.
 */
var util = require('util'),
  Oauth1Strategy = require('../lib/passport-oauth1'); // SPECIAL OAUTH PATCHED TO READ IN A KEY AND SECRET

function Strategy(options, verify) {
  options = options || {};
  options.requestTokenURL = 'https://api.xero.com/oauth/RequestToken';
  options.accessTokenURL = 'https://api.xero.com/oauth/AccessToken';
  options.userAuthorizationURL = 'https://api.xero.com/oauth/Authorize';

  Oauth1Strategy.call(this, options, verify);

  this.name = 'xero';
}

util.inherits(Strategy, Oauth1Strategy);

module.exports = Strategy;
<|endoftext|>


<commit_before>'use strict';

/**
 * The mock approval object
 * @param {mockServer} server
 * @param {Function} readyCallback
 */
function mockApproval(server, readyCallback) {

    var apiPath = '../../../../api/';

    this.api = {
        user: require(apiPath+'User.api.js'),
        department: require(apiPath+'Department.api.js')
    };
    this.Q = require('q');
    this.server = server;
}

mockApproval.prototype.createRight = function(name, quantity, quantity_unit) {

    var RightModel = this.server.app.db.mongoose.model('Right');
    var right = new RightModel();
    right.name = name;
    right.quantity = quantity;
    right.quantity_unit = quantity_unit;
    return right.save();
};

mockApproval.prototype.createCollection = function(name) {

    var RightCollectionModel = this.server.app.db.mongoose.model('RightCollection');
    var collection = new RightCollectionModel();
    collection.name = name;
    return collection.save();
};

/**
 * Create a departments tree to mock approval
 * @todo: make non-linear
 *
 *   d0
 *   /\
 * d1  d2
 *  |  | \
 * d3 d4  d5
 *   /  \
 *  d6  d7
 */
mockApproval.prototype.createDepartments = function(app) {

    var deferred = this.Q.defer();

    // prepare parents by index

    var position = [
        null,   // d0
        0,      // d1
        0,      // d2
        1,      // d3
        2,      // d4
        2,      // d5
        4,      // d6
        4       // d7
    ];

    // create 7 departments

    var departments = [], parent = null, count = 0, api = this.api;

    function nextCreation(department) {

        api.user.createRandomManager(app).then(function(randomManager) {

            if (randomManager.user.roles.manager === undefined) {
                return deferred.reject('Not a manager');
            }

            randomManager.user.populate('roles.manager', function() {

                randomManager.user.roles.manager.department.push(department._id);
                randomManager.user.roles.manager.save(function() {

                    departments.push(department);
                    count++;

                    parent = departments[position[count]];

                    if (count <= 7) {
                        return api.department.create(app, parent).then(nextCreation);
                    }

                    deferred.resolve(departments);

                });
            });

        }, deferred.reject);
    }

    api.department.create(app, parent).then(nextCreation);

    return deferred.promise;

};

exports = module.exports = mockApproval;
<commit_msg>mock approval<commit_after>'use strict';

/**
 * The mock approval object
 * @param {mockServer} server
 * @param {Function} readyCallback
 */
function mockApproval(server, readyCallback) {

    var apiPath = '../../../../api/';

    this.api = {
        user: require(apiPath+'User.api.js'),
        department: require(apiPath+'Department.api.js')
    };
    this.Q = require('q');
    this.server = server;
}

/**
 * Create a right
 */
mockApproval.prototype.createRight = function(name, quantity, quantity_unit) {

    var RightModel = this.server.app.db.mongoose.model('Right');
    var right = new RightModel();
    right.name = name;
    right.quantity = quantity;
    right.quantity_unit = quantity_unit;
    return right.save();
};

/**
 * Create a right collection
 * with 4 rights
 *
 * @return {Promise}
 */
mockApproval.prototype.createCollection = function(name) {

    var deferred = this.Q.defer();
    var self = this;
    var RightCollectionModel = this.server.app.db.mongoose.model('RightCollection');
    var collection = new RightCollectionModel();
    collection.name = name;
    collection.save(function(err, collection) {
        var promises = [];
        promises.push(self.createRight('right 1', 25, 'D'));
        promises.push(self.createRight('right 2', 5.25, 'D'));
        promises.push(self.createRight('right 3', 2, 'D'));
        promises.push(self.createRight('right 4', 100, 'H'));

        Q.All(promises).then(function(rights) {

            //TODO add beneficiaries
            deferred.resolve(collection);
        });
    });

    return deferred.promise;
};

/**
 * Create a departments tree to mock approval
 * @todo: make non-linear
 *
 *   d0
 *   /\
 * d1  d2
 *  |  | \
 * d3 d4  d5
 *   /  \
 *  d6  d7
 */
mockApproval.prototype.createDepartments = function(app) {

    var deferred = this.Q.defer();

    // prepare parents by index

    var position = [
        null,   // d0
        0,      // d1
        0,      // d2
        1,      // d3
        2,      // d4
        2,      // d5
        4,      // d6
        4       // d7
    ];

    // create 7 departments

    var departments = [], parent = null, count = 0, api = this.api;

    function nextCreation(department) {

        api.user.createRandomManager(app).then(function(randomManager) {

            if (randomManager.user.roles.manager === undefined) {
                return deferred.reject('Not a manager');
            }

            randomManager.user.populate('roles.manager', function() {

                randomManager.user.roles.manager.department.push(department._id);
                randomManager.user.roles.manager.save(function() {

                    departments.push(department);
                    count++;

                    parent = departments[position[count]];

                    if (count <= 7) {
                        return api.department.create(app, parent).then(nextCreation);
                    }

                    deferred.resolve(departments);

                });
            });

        }, deferred.reject);
    }

    api.department.create(app, parent).then(nextCreation);

    return deferred.promise;

};

exports = module.exports = mockApproval;
<|endoftext|>


<commit_before>/**
* @copyright Urucas
* @license   MIT License
* @version   Release: 1.0.1
* @link       http://urucas.com
* @developers Bruno Alassia, Pamela Prosperi
*/

try {

	jQuery.fn.render = function(source, data, config) {
		try {
			config = config || { append:false, prepend: false, modifiers: [], callback: undefined }
			var response;
			var el = this;

			// load html file to render  synchronously
			$.ajax({
				url:source,
				data:[],
				success:function(response){
					html = response;
				},
				async: false
			});

			// create replace function
			var replace = function(key, value, str, modifier) {
				var reg = new RegExp("{%"+key+"}");
				try {
					if(modifier != undefined && modifier instanceof Function) {
						value = modifier(value);
					}
				}catch(e) { console.log("jquery.render.js modifier error: "+e); }
				return str.replace(reg, value);
			}

			var modifiers = config.modifiers;

			// render a list of object
			if(data instanceof Array) {
				var len = data.length;
				var aux2= "";
				for(var i=0; i< len; i++) {
					var aux = html;
					var d = data[i];
					for(key in d) {
						aux = replace(key, d[key], aux, modifiers[key]);
					}
					aux2+=aux;
				}
				html = aux2;
			}
			// render a simple object
			else if(data instanceof Object) {
				var aux = html;
				for(key in data) {
					aux = replace(key, data[key], aux, modifiers[key]);
				}
				html = aux;
			}

			// html content can be render in 3 ways;
			// * append: true, append content at the end of the container,
			// * prepend: true, append content at the begining of the container,
			// * none will replace the content of the container
			if(config.append) { $(el).append(html);	 }
			else if(config.prepend) { $(el).prepend(html); }
			else { $(el).html(html); }

			if(config.callback != undefined && config.callback instanceof Function) {
				callback();
			}

		}catch(e) {
			console.log(e);
		}
		return this;
	}

}catch(e) {
	console.log("jQuery is not defined, make sure to include the jquery library before including JQuery render extension");
}

try {

	jQuery.fn.include = function(view, callback) {
		var el = this;
		$(el).load(view, function(){
			$(el).find("include").each(function(){
				var inc = this.getAttribute("src");
				var oel = this;
				$.ajax({
					url:inc,
					data:[],
					async:false,
					success: function(data){
						$(oel).replaceWith(data);
					}
				});
			});
		});
		if(callback!= undefined && callback instanceof Function) {
			callback();
		}
		return this;
	}

}catch(e) {
	console.log(e);
}
<commit_msg>put include callback in the rigth place<commit_after>/**
* @copyright Urucas
* @license   MIT License
* @version   Release: 1.0.1
* @link       http://urucas.com
* @developers Bruno Alassia, Pamela Prosperi
*/

try {

	jQuery.fn.render = function(source, data, config) {
		try {
			config = config || { append:false, prepend: false, modifiers: [], callback: undefined }
			var response;
			var el = this;

			// load html file to render  synchronously
			$.ajax({
				url:source,
				data:[],
				success:function(response){
					html = response;
				},
				async: false
			});

			// create replace function
			var replace = function(key, value, str, modifier) {
				var reg = new RegExp("{%"+key+"}");
				try {
					if(modifier != undefined && modifier instanceof Function) {
						value = modifier(value);
					}
				}catch(e) { console.log("jquery.render.js modifier error: "+e); }
				return str.replace(reg, value);
			}

			var modifiers = config.modifiers;

			// render a list of object
			if(data instanceof Array) {
				var len = data.length;
				var aux2= "";
				for(var i=0; i< len; i++) {
					var aux = html;
					var d = data[i];
					for(key in d) {
						aux = replace(key, d[key], aux, modifiers[key]);
					}
					aux2+=aux;
				}
				html = aux2;
			}
			// render a simple object
			else if(data instanceof Object) {
				var aux = html;
				for(key in data) {
					aux = replace(key, data[key], aux, modifiers[key]);
				}
				html = aux;
			}

			// html content can be render in 3 ways;
			// * append: true, append content at the end of the container,
			// * prepend: true, append content at the begining of the container,
			// * none will replace the content of the container
			if(config.append) { $(el).append(html);	 }
			else if(config.prepend) { $(el).prepend(html); }
			else { $(el).html(html); }

			if(config.callback != undefined && config.callback instanceof Function) {
				callback();
			}

		}catch(e) {
			console.log(e);
		}
		return this;
	}

}catch(e) {
	console.log("jQuery is not defined, make sure to include the jquery library before including JQuery render extension");
}

try {

	jQuery.fn.include = function(view, callback) {
		var el = this;
		$(el).load(view, function(){
			$(el).find("include").each(function(){
				var inc = this.getAttribute("src");
				var oel = this;
				$.ajax({
					url:inc,
					data:[],
					async:false,
					success: function(data){
						$(oel).replaceWith(data);

						if(callback!= undefined && callback instanceof Function) {
							callback();
						}
					}
				});
			});
		});

		return this;
	}

}catch(e) {
	console.log(e);
}
<|endoftext|>


<commit_before>function circleLayer(color, source, vectorLayer) {
  var layer = {
    id: [source, vectorLayer, 'circle'].join('_'),
    source: source,
    type: 'circle',
    paint: {
      'circle-color': color,
      'circle-radius': 2
    },
    filter: ['==', '$type', 'Point']
  };
  if (vectorLayer) {
    layer['source-layer'] = vectorLayer;
  }
  return layer;
}

function polygonLayer(color, outlineColor, source, vectorLayer) {
  var layer = {
    id: [source, vectorLayer, 'polygon'].join('_'),
    source: source,
    type: 'fill',
    paint: {
      'fill-color': color,
      'fill-antialias': true,
      'fill-outline-color': color
    },
    filter: ['==', '$type', 'Polygon']
  };
  if (vectorLayer) {
    layer['source-layer'] = vectorLayer;
  }
  return layer;
}

function lineLayer(color, source, vectorLayer) {
  var layer = {
    id: [source, vectorLayer, 'line'].join('_'),
    source: source,
    layout: {
      'line-join': 'round',
      'line-cap': 'round'
    },
    type: 'line',
    paint: {
      'line-color': color
    },
    filter: ['==', '$type', 'LineString']
  };
  if (vectorLayer) {
    layer['source-layer'] = vectorLayer;
  }
  return layer;
}

/**
 * Generate colored layer styles for the given sources
 * TODO: Improve docs
 * @param {Object} Sources dict containing the vector layer IDs
 * @param {Function} Function to generate a color for a layer
 * @return {array} Array of Mapbox GL layers
 */
function generateColoredLayers(sources, assignLayerColor) {
  var polyLayers = [];
  var circleLayers = [];
  var lineLayers = [];

  function alphaColors(layerId) {
    var color = assignLayerColor.bind(null, layerId);
    var obj = {
      circle: color(0.8),
      line: color(0.6),
      polygon: color(0.3),
      polygonOutline: color(0.6),
      default: color(1)
    };
    return obj;
  }

  Object.keys(sources).forEach(function (sourceId) {
    var layers = sources[sourceId];

    if (!layers || layers.length === 0) {
      var colors = alphaColors(sourceId);
      circleLayers.push(circleLayer(colors.circle, sourceId));
      lineLayers.push(lineLayer(colors.line, sourceId));
      polyLayers.push(polygonLayer(colors.polygon, colors.polygonOutline, sourceId));
    } else {
      layers.forEach(function (layerId) {
        var colors = alphaColors(layerId);

        circleLayers.push(circleLayer(colors.circle, sourceId, layerId));
        lineLayers.push(lineLayer(colors.line, sourceId, layerId));
        polyLayers.push(polygonLayer(colors.polygon, colors.polygonOutline, sourceId, layerId));
      });
    }
  });

  return polyLayers.concat(lineLayers).concat(circleLayers);
}

/**
 * Create inspection style out of the original style and the new colored layers
 * @param {Object} Original map styles
 * @param {array} Array of colored Mapbox GL layers
 * @return {Object} Colored inspect style
 */
function generateInspectStyle(originalMapStyle, coloredLayers, opts) {
  opts = Object.assign({
    backgroundColor: '#fff'
  }, opts);

  var backgroundLayer = {
    'id': 'background',
    'type': 'background',
    'paint': {
      'background-color': opts.backgroundColor
    }
  };

  var sources = {};
  Object.keys(originalMapStyle.sources).forEach(function (sourceId) {
    var source = originalMapStyle.sources[sourceId];
    if (source.type !== 'raster') {
      sources[sourceId] = source;
    }
  });

  return Object.assign(originalMapStyle, {
    layers: [backgroundLayer].concat(coloredLayers),
    soources: sources
  });
}

exports.polygonLayer = polygonLayer;
exports.lineLayer = lineLayer;
exports.circleLayer = circleLayer;
exports.generateInspectStyle = generateInspectStyle;
exports.generateColoredLayers = generateColoredLayers;
<commit_msg>Fix to include only vector sources in inspect style.<commit_after>function circleLayer(color, source, vectorLayer) {
  var layer = {
    id: [source, vectorLayer, 'circle'].join('_'),
    source: source,
    type: 'circle',
    paint: {
      'circle-color': color,
      'circle-radius': 2
    },
    filter: ['==', '$type', 'Point']
  };
  if (vectorLayer) {
    layer['source-layer'] = vectorLayer;
  }
  return layer;
}

function polygonLayer(color, outlineColor, source, vectorLayer) {
  var layer = {
    id: [source, vectorLayer, 'polygon'].join('_'),
    source: source,
    type: 'fill',
    paint: {
      'fill-color': color,
      'fill-antialias': true,
      'fill-outline-color': color
    },
    filter: ['==', '$type', 'Polygon']
  };
  if (vectorLayer) {
    layer['source-layer'] = vectorLayer;
  }
  return layer;
}

function lineLayer(color, source, vectorLayer) {
  var layer = {
    id: [source, vectorLayer, 'line'].join('_'),
    source: source,
    layout: {
      'line-join': 'round',
      'line-cap': 'round'
    },
    type: 'line',
    paint: {
      'line-color': color
    },
    filter: ['==', '$type', 'LineString']
  };
  if (vectorLayer) {
    layer['source-layer'] = vectorLayer;
  }
  return layer;
}

/**
 * Generate colored layer styles for the given sources
 * TODO: Improve docs
 * @param {Object} Sources dict containing the vector layer IDs
 * @param {Function} Function to generate a color for a layer
 * @return {array} Array of Mapbox GL layers
 */
function generateColoredLayers(sources, assignLayerColor) {
  var polyLayers = [];
  var circleLayers = [];
  var lineLayers = [];

  function alphaColors(layerId) {
    var color = assignLayerColor.bind(null, layerId);
    var obj = {
      circle: color(0.8),
      line: color(0.6),
      polygon: color(0.3),
      polygonOutline: color(0.6),
      default: color(1)
    };
    return obj;
  }

  Object.keys(sources).forEach(function (sourceId) {
    var layers = sources[sourceId];

    if (!layers || layers.length === 0) {
      var colors = alphaColors(sourceId);
      circleLayers.push(circleLayer(colors.circle, sourceId));
      lineLayers.push(lineLayer(colors.line, sourceId));
      polyLayers.push(polygonLayer(colors.polygon, colors.polygonOutline, sourceId));
    } else {
      layers.forEach(function (layerId) {
        var colors = alphaColors(layerId);

        circleLayers.push(circleLayer(colors.circle, sourceId, layerId));
        lineLayers.push(lineLayer(colors.line, sourceId, layerId));
        polyLayers.push(polygonLayer(colors.polygon, colors.polygonOutline, sourceId, layerId));
      });
    }
  });

  return polyLayers.concat(lineLayers).concat(circleLayers);
}

/**
 * Create inspection style out of the original style and the new colored layers
 * @param {Object} Original map styles
 * @param {array} Array of colored Mapbox GL layers
 * @return {Object} Colored inspect style
 */
function generateInspectStyle(originalMapStyle, coloredLayers, opts) {
  opts = Object.assign({
    backgroundColor: '#fff'
  }, opts);

  var backgroundLayer = {
    'id': 'background',
    'type': 'background',
    'paint': {
      'background-color': opts.backgroundColor
    }
  };

  var sources = {};
  Object.keys(originalMapStyle.sources).forEach(function (sourceId) {
    var source = originalMapStyle.sources[sourceId];
    if (source.type === "vector" || source.type === "geojson") {
      sources[sourceId] = source;
    }
  });

  return Object.assign(originalMapStyle, {
    layers: [backgroundLayer].concat(coloredLayers),
    soources: sources
  });
}

exports.polygonLayer = polygonLayer;
exports.lineLayer = lineLayer;
exports.circleLayer = circleLayer;
exports.generateInspectStyle = generateInspectStyle;
exports.generateColoredLayers = generateColoredLayers;
<|endoftext|>


<commit_before>// DEV : LEANDRO SILVA SOARES
// REPO: git@github.com:LeandroSoares/slidez.git
//----------------------------------------------------------------------------
// Usage:
//		$('#myholder').slidez({slidezClass:'.myscreens', width:1280, height:720, transitiontime:1000,loopThrough:false});
//		$('#myholder').slidezCtrls({NextArr:[list of next buttons],
// 									PrevArr:[list of prev buttons],
// 									nextBtn:'#nextButton',
// 									prevBtn:'#prevButton'
// });
//----------------------------------------------------------------------------
var SlidezEvents = {
						ENTER:'slidezEnter',
						EXIT:'slidezExit',
						ENTER_COMPLETE:'slidezEnterComplete'
				   };
(function( $ ) {
    //CONSTRUCTOR
    $.fn.slidez = function(options) {

	    var settings = $.extend({
		       slidezClass:".screen"
		       ,width:1024
		       ,height:768
		       ,transitiontime:500
		       ,loopThrough:false
		    }, options);

	    if(!$(this).children(settings.slidezClass).length)
			throw 'slidez container: #'+$(this).attr('id')+' is empty !\nRemember to addClass ".screen" to your screens element holder.';

	    //STORE SCREENS ARRAY
	 	$(this).data('screens',$(this).children(settings.slidezClass));
		$(this).data('current',0);
		$(this).data('transitiontime',settings.transitiontime);
		$($(this).data('screens')).each(function(index, Element){
			$(Element).data("index", index);
		});
		$(this).data('loopThrough', settings.loopThrough);
		//SETTING HOLDER
	 	this.css({
	 		width:settings.width
	 	   ,height:settings.height
	 	   ,position:'absolute'
	 	   ,overflow:'hidden'
	 	});

	 	//SETTING SCREENS
	 	$(this).children(settings.slidezClass).each(function() {
	 		$(this).css({
		 		width:settings.width
		 	   ,height:settings.height
		 	   ,position:'absolute'
		 	});
	 	});
	 	//DISPLAY FIRST SCREEN
	 	$(this).slidezReset();
        return this;
    }

    $.fn.slidezLast = function() {
		$(this).slidezGoTo($(this).data('screens').length-1);
		return this;
	}

	$.fn.slidezFirst = function() {
		$(this).slidezGoTo(0);
		return this;
	}

	$.fn.slidezNext = function() {

		var screens = $(this).data('screens');
		var current = $(this).data('current');
		var loop =  $(this).data('loopThrough');
		if(current<screens.length-1)
			$(this).slidezGoTo(current+1);
		else if(loop)
			$(this).slidezFirst();

		return this;
	}

	$.fn.slidezPrev = function() {

		var current = $(this).data('current');
		var loop =  $(this).data('loopThrough');
		if(current>0)
			$(this).slidezGoTo(current-1);
		else if(loop)
			$(this).slidezLast();

		return this;
	}

	$.fn.slidezShow = function(_id)
	{
		var _index=$(_id).data('index');
		var screens = $(this).data('screens');
		var transitiontime = $(this).data('transitiontime');
		$(screens[_index]).stop().fadeIn(transitiontime);
	}

	$.fn.slidezHide = function(_id)
	{
		var _index=$(_id).data('index');
		var screens = $(this).data('screens');
		var transitiontime = $(this).data('transitiontime');
		$(screens[_index]).stop().fadeOut(transitiontime);
	}
//Usage: can either go to index or id
// $('#MySlidezHolder').slidezGoTo(1);
// $('#MySlidezHolder').slidezGoTo('#slideSpecial');
	$.fn.slidezGoTo = function(__index) {
		var _index;
		//Validando
		if(__index.constructor===Number)
			_index = __index;
		else if(__index.constructor===String)
			_index = $(__index).data('index')
		else
			throw "Error, __index is not a Number or a String ID";

		var screens = $(this).data('screens');
		var current = $(this).data('current');
		var transitiontime = $(this).data('transitiontime');

		if(_index<0 || _index > screens.length-1)
			throw 'slidez: _index:'+_index+' out of range <from 0 up to '+screens.length-1+'>';
		if(current!=_index) {
			$(screens[current]).stop().fadeOut(transitiontime);
			$(screens[_index]).stop().fadeIn(transitiontime, function(){
//trigger>>>>>>>>>>
				$(this).trigger(SlidezEvents.ENTER_COMPLETE, $(screens[_index]));
			});

			$(this).delay(transitiontime-10).trigger(SlidezEvents.EXIT,$(screens[current]));

			$(this).trigger(SlidezEvents.ENTER,$(screens[_index]));
//trigger>>>>>>>>>>
			current=_index;
		}

		$(this).data('current',current);

		return this;
	}
	//RESET: SETS DISPLAY NONE TO ALL BUT ONE
	$.fn.slidezReset = function(_index) {
		$(this).data('screens').each(function(){ $(this).hide();});
		$($(this).data('screens')[_index||0]).stop().show();
		return this;
	}
// options = {
//				NextArr:[buttom1, etc..],
//				PrevArr:[],
//				nextBtn:'#b1',
//				prevBtn:element
//            }
	$.fn.slidezCtrls=function (options) {

		var container = $(this);

		if(options.NextArr && options.NextArr.length>0)
			for (var i = options.NextArr.length - 1; i >= 0; i--)
				setNextBtn(options.NextArr[i]);
		else
			setNextBtn(options.nextBtn);
		if(options.PrevArr && options.PrevArr.length>0)
			for (var i = options.PrevArr.length - 1; i >= 0; i--)
				setPrevBtn(options.PrevArr[i]);
		else
			setPrevBtn(options.prevBtn);

		function setNextBtn(id) {
			$(id||'#next').bind("click",function() {
				$(container).slidezNext();
			});
		}
		function setPrevBtn(id) {
			$(id||'#prev').bind("click",function() {
				$(container).slidezPrev();
			});
		}
	}

	//GET CURRENT SLIDEZ
    $.fn.slidez_current=function() {
    	return $(this).data('current');
    }
	//GET TOTAL SLIDEZS
	$.fn.slidez_screensCount=function() {
		return $(this).data('screens').length;
	}
    //GET SET TRANSITIONTIME
    $.fn.slidez_transitionTime=function(time) {
    	if(time) $(this).data('transitiontime',time); return this;
    	return $(this).data('transitiontime');
    }
}( jQuery ));<commit_msg>ajuste de dimensoes<commit_after>// DEV : LEANDRO SILVA SOARES
// REPO: git@github.com:LeandroSoares/slidez.git
//----------------------------------------------------------------------------
// Usage:
//		$('#myholder').slidez({slidezClass:'.myscreens', width:1280, height:720, transitiontime:1000,loopThrough:false});
//		$('#myholder').slidezCtrls({NextArr:[list of next buttons],
// 									PrevArr:[list of prev buttons],
// 									nextBtn:'#nextButton',
// 									prevBtn:'#prevButton'
// });
//----------------------------------------------------------------------------
var SlidezEvents = {
						ENTER:'slidezEnter',
						EXIT:'slidezExit',
						ENTER_COMPLETE:'slidezEnterComplete'
				   };
(function( $ ) {
    //CONSTRUCTOR
    $.fn.slidez = function(options) {

	    var settings = $.extend({
		       slidezClass:".screen"
		       ,width:null
		       ,height:null
		       ,transitiontime:500
		       ,loopThrough:false
		    }, options);

	    if(!$(this).children(settings.slidezClass).length)
			throw 'slidez container: #'+$(this).attr('id')+' is empty !\nRemember to addClass ".screen" to your screens element holder.';

	    //STORE SCREENS ARRAY
	 	$(this).data('screens',$(this).children(settings.slidezClass));
		$(this).data('current',0);
		$(this).data('transitiontime',settings.transitiontime);
		$($(this).data('screens')).each(function(index, Element){
			$(Element).data("index", index);
		});
		$(this).data('loopThrough', settings.loopThrough);

		//SETTING HOLDER
	 	this.css({
	 	   position:'absolute'
	 	   ,overflow:'hidden'
	 	});
		if(settings.width!=null && settings.height!=null){
		 	this.css({
				 width:settings.width
				,height:settings.height
		 	});

		 }

	 	//SETTING SCREENS
	 	$(this).children(settings.slidezClass).each(function() {
	 		if(settings.width!=null && settings.height!=null) {
	 			$(this).css({ width:settings.width ,height:settings.height });
	 		}
	 		$(this).css({position:'absolute'});
	 	});
	 	//DISPLAY FIRST SCREEN
	 	$(this).slidezReset();
        return this;
    }

    $.fn.slidezLast = function() {
		$(this).slidezGoTo($(this).data('screens').length-1);
		return this;
	}

	$.fn.slidezFirst = function() {
		$(this).slidezGoTo(0);
		return this;
	}

	$.fn.slidezNext = function() {

		var screens = $(this).data('screens');
		var current = $(this).data('current');
		var loop =  $(this).data('loopThrough');
		if(current<screens.length-1)
			$(this).slidezGoTo(current+1);
		else if(loop)
			$(this).slidezFirst();

		return this;
	}

	$.fn.slidezPrev = function() {

		var current = $(this).data('current');
		var loop =  $(this).data('loopThrough');
		if(current>0)
			$(this).slidezGoTo(current-1);
		else if(loop)
			$(this).slidezLast();

		return this;
	}

	$.fn.slidezShow = function(_id)
	{
		var _index=$(_id).data('index');
		var screens = $(this).data('screens');
		var transitiontime = $(this).data('transitiontime');
		$(screens[_index]).stop().fadeIn(transitiontime);
	}

	$.fn.slidezHide = function(_id)
	{
		var _index=$(_id).data('index');
		var screens = $(this).data('screens');
		var transitiontime = $(this).data('transitiontime');
		$(screens[_index]).stop().fadeOut(transitiontime);
	}
//Usage: can either go to index or id
// $('#MySlidezHolder').slidezGoTo(1);
// $('#MySlidezHolder').slidezGoTo('#slideSpecial');
	$.fn.slidezGoTo = function(__index) {
		var _index;
		//Validando
		if(__index.constructor===Number)
			_index = __index;
		else if(__index.constructor===String)
			_index = $(__index).data('index')
		else
			throw "Error, __index is not a Number or a String ID";

		var screens = $(this).data('screens');
		var current = $(this).data('current');
		var transitiontime = $(this).data('transitiontime');

		if(_index<0 || _index > screens.length-1)
			throw 'slidez: _index:'+_index+' out of range <from 0 up to '+screens.length-1+'>';
		if(current!=_index) {
			$(screens[current]).stop().fadeOut(transitiontime);
			$(screens[_index]).stop().fadeIn(transitiontime, function(){
//trigger>>>>>>>>>>
				$(this).trigger(SlidezEvents.ENTER_COMPLETE, $(screens[_index]));
			});

			$(this).delay(transitiontime-10).trigger(SlidezEvents.EXIT,$(screens[current]));

			$(this).trigger(SlidezEvents.ENTER,$(screens[_index]));
//trigger>>>>>>>>>>
			current=_index;
		}

		$(this).data('current',current);

		return this;
	}
	//RESET: SETS DISPLAY NONE TO ALL BUT ONE
	$.fn.slidezReset = function(_index) {
		$(this).data('screens').each(function(){ $(this).hide();});
		$($(this).data('screens')[_index||0]).stop().show();
		return this;
	}
// options = {
//				NextArr:[buttom1, etc..],
//				PrevArr:[],
//				nextBtn:'#b1',
//				prevBtn:element
//            }
	$.fn.slidezCtrls=function (options) {

		var container = $(this);

		if(options.NextArr && options.NextArr.length>0)
			for (var i = options.NextArr.length - 1; i >= 0; i--)
				setNextBtn(options.NextArr[i]);
		else
			setNextBtn(options.nextBtn);
		if(options.PrevArr && options.PrevArr.length>0)
			for (var i = options.PrevArr.length - 1; i >= 0; i--)
				setPrevBtn(options.PrevArr[i]);
		else
			setPrevBtn(options.prevBtn);

		function setNextBtn(id) {
			$(id||'#next').bind("click",function() {
				$(container).slidezNext();
			});
		}
		function setPrevBtn(id) {
			$(id||'#prev').bind("click",function() {
				$(container).slidezPrev();
			});
		}
	}

	//GET CURRENT SLIDEZ
    $.fn.slidez_current=function() {
    	return $(this).data('current');
    }
	//GET TOTAL SLIDEZS
	$.fn.slidez_screensCount=function() {
		return $(this).data('screens').length;
	}
    //GET SET TRANSITIONTIME
    $.fn.slidez_transitionTime=function(time) {
    	if(time) $(this).data('transitiontime',time); return this;
    	return $(this).data('transitiontime');
    }
}( jQuery ));<|endoftext|>


<commit_before>
var log = require("./log")
  , fs = require("graceful-fs")
  , path = require("path")
  , npm = require("../../npm")
  , exec = require("./exec")
  , uidNumber = require("./uid-number")
  , umask = process.umask()
  , umaskOrig = umask
  , addedUmaskExit = false
  , mkdirCache = {}

module.exports = mkdir
function mkdir (ensure, mode, uid, gid, cb_) {
  if (typeof cb_ !== "function") cb_ = gid, gid = null
  if (typeof cb_ !== "function") cb_ = uid, uid = null
  if (typeof cb_ !== "function") cb_ = mode, mode = 0755

  if (mode & umask) {
    log.verbose(mode.toString(8), "umasking from "+umask.toString(8))
    process.umask(umask = 0)
    if (!addedUmaskExit) {
      addedUmaskExit = true
      process.on("exit", function () { process.umask(umask = umaskOrig) })
    }
  }

  ensure = ensure.replace(/\/+$/, '')
  if (ensure.charAt(0) !== "/") ensure = path.join(process.cwd(), ensure)

  if (mkdirCache.hasOwnProperty(ensure)) {
    return mkdirCache[ensure].push(cb_)
  }
  mkdirCache[ensure] = [cb_]

  function cb (er) {
    var cbs = mkdirCache[ensure]
    delete mkdirCache[ensure]
    cbs.forEach(function (c) { c(er) })
  }

  if (uid === null && gid === null) {
    return mkdir_(ensure, mode, uid, gid, cb)
  }

  uidNumber(uid, gid, function (er, uid, gid) {
    if (er) return cb(er)
    mkdir_(ensure, mode, uid, gid, cb)
  })
}

function mkdir_ (ensure, mode, uid, gid, cb) {
  // if it's already a dir, then just check the bits and owner.
  fs.stat(ensure, function (er, s) {
    if (s && s.isDirectory()) {
      // check mode
      if ((s.mode & mode) === mode) return cb()
      return done(ensure, mode, uid, gid, cb)
    }
    return walkDirs(ensure, mode, uid, gid, cb)
  })
}

function done (ensure, mode, uid, gid, cb) {
  // now the directory has been created.
  // chown it to the desired uid/gid
  // Don't chown the npm.root dir, though, in case we're
  // in unsafe-perm mode.
  log.verbose("done: "+ensure+" "+mode.toString(8), "mkdir")
  fs.chmod(ensure, mode, function (er) {
    if (er || ensure === npm.dir || uid == null
        || npm.config.get("unsafe-perm")) return cb(er)
    if (typeof uid !== "number" || typeof gid !== "number") {
      return cb(er)
    }
    uid = Math.floor(uid)
    gid = Math.floor(gid)
    fs.chown(ensure, uid, gid, cb)
  })
}

function walkDirs (ensure, mode, uid, gid, cb) {
  var dirs = ensure.split("/")
    , walker = []
    , foundUID = null
    , foundGID = null
  walker.push(dirs.shift()) // gobble the "/" first
  ;(function S (d) {
    if (d === undefined) {
      return done(ensure, mode, uid, gid, cb)
    }
    walker.push(d)
    var dir = walker.join("/")
    fs.stat(dir, function STATCB (er, s) {
      if (er) {
        if (foundUID !== null) uid = foundUID
        if (foundGID !== null) gid = foundGID
        fs.mkdir(dir, mode, function MKDIRCB (er, s) {
          if (er && er.message.indexOf("EEXIST") === 0) {
            // handle stat race
            return fs.stat(dir, STATCB)
          }
          if (er) return cb(er)
          if (uid && gid && !npm.config.get("unsafe-perm")) {
            fs.chown(dir, uid, gid, function (er) {
              S(dirs.shift())
            })
          } else {
            S(dirs.shift())
          }
        })
      } else {
        if (s.isDirectory()) {
          if (uid === null && typeof s.uid === "number") foundUID = s.uid
          if (gid === null && typeof s.gid === "number") foundGID = s.gid
          S(dirs.shift())
        } else cb(new Error("Failed to mkdir "+dir+": File exists"))
      }
    })
  })(dirs.shift())
}
<commit_msg>Add a bunch of logging and commentary for #1153<commit_after>
var log = require("./log")
  , fs = require("graceful-fs")
  , path = require("path")
  , npm = require("../../npm")
  , exec = require("./exec")
  , uidNumber = require("./uid-number")
  , umask = process.umask()
  , umaskOrig = umask
  , addedUmaskExit = false
  , mkdirCache = {}

module.exports = mkdir
function mkdir (ensure, mode, uid, gid, cb_) {
  if (typeof cb_ !== "function") cb_ = gid, gid = null
  if (typeof cb_ !== "function") cb_ = uid, uid = null
  if (typeof cb_ !== "function") cb_ = mode, mode = 0755

  if (mode & umask) {
    log.verbose(mode.toString(8), "umasking from "+umask.toString(8))
    process.umask(umask = 0)
    if (!addedUmaskExit) {
      addedUmaskExit = true
      process.on("exit", function () { process.umask(umask = umaskOrig) })
    }
  }

  ensure = ensure.replace(/\/+$/, '')
  if (ensure.charAt(0) !== "/") ensure = path.join(process.cwd(), ensure)

  if (mkdirCache.hasOwnProperty(ensure)) {
    return mkdirCache[ensure].push(cb_)
  }
  mkdirCache[ensure] = [cb_]

  function cb (er) {
    var cbs = mkdirCache[ensure]
    delete mkdirCache[ensure]
    cbs.forEach(function (c) { c(er) })
  }

  if (uid === null && gid === null) {
    return mkdir_(ensure, mode, uid, gid, cb)
  }

  uidNumber(uid, gid, function (er, uid, gid) {
    if (er) return cb(er)
    mkdir_(ensure, mode, uid, gid, cb)
  })
}

function mkdir_ (ensure, mode, uid, gid, cb) {
  // if it's already a dir, then just check the bits and owner.
  fs.stat(ensure, function (er, s) {
    if (s && s.isDirectory()) {
      // check mode
      if ((s.mode & mode) === mode) return cb()
      return done(ensure, mode, uid, gid, cb)
    }
    return walkDirs(ensure, mode, uid, gid, cb)
  })
}

function done (ensure, mode, uid, gid, cb) {
  // now the directory has been created.
  // chown it to the desired uid/gid
  // Don't chown the npm.root dir, though, in case we're
  // in unsafe-perm mode.
  log.verbose("done: "+ensure+" "+mode.toString(8), "mkdir")
  fs.chmod(ensure, mode, function (er) {
    if (er || ensure === npm.dir || uid == null
        || npm.config.get("unsafe-perm")) return cb(er)
    if (typeof uid !== "number" || typeof gid !== "number") {
      return cb(er)
    }
    uid = Math.floor(uid)
    gid = Math.floor(gid)
    fs.chown(ensure, uid, gid, cb)
  })
}

function walkDirs (ensure, mode, uid, gid, cb) {
  var dirs = ensure.split("/")
    , walker = []
    , foundUID = null
    , foundGID = null

  // gobble the "/" first
  walker.push(dirs.shift())

  // The loop that goes through and stats each dir.
  ;(function S (d) {
    // no more directory steps left.
    if (d === undefined) {
      // do the chown stuff
      return done(ensure, mode, uid, gid, cb)
    }

    // get the absolute dir for the next piece being stat'd
    walker.push(d)
    var dir = walker.join("/")

    log.verbose(dir, "mkdir walkDirs")
    // stat callback lambda
    fs.stat(dir, function STATCB (er, s) {
      if (er) {
        // the stat failed - directory does not exist.

        log.verbose(er.message, "mkdir (expected) error")

        // use the same uid/gid as the nearest parent, if not set.
        if (foundUID !== null) uid = foundUID
        if (foundGID !== null) gid = foundGID

        // make the directory
        fs.mkdir(dir, mode, function MKDIRCB (er, s) {
          // since stat and mkdir are done as two separate syscalls,
          // operating on a path rather than a file descriptor, it's
          // possible that the directory didn't exist when we did
          // the stat, but then *did* exist when we go to to the mkdir.
          // If we didn't care about uid/gid, we could just mkdir
          // repeatedly, failing on any error other than "EEXIST".
          if (er && er.message.indexOf("EEXIST") === 0) {
            return fs.stat(dir, STATCB)
          }

          // any other kind of error is not saveable.
          if (er) return cb(er)

          // at this point, we've just created a new directory successfully.

          // if we care about permissions
          if (!npm.config.get("unsafe-perm") // care about permissions
              // specified a uid and gid
              && uid !== null
              && gid !== null
              // at least one of them is wrong
              && ( uid !== s.uid || gid !== s.gid ) ) {
            // set the proper ownership
            return fs.chown(dir, uid, gid, function (er) {
              if (er) return cb(er)
              // attack the next portion of the path.
              S(dirs.shift())
            })
          } else {
            // either we don't care about ownership, or it's already right.
            S(dirs.shift())
          }
        }) // mkdir

      } else {
        // the stat succeeded.
        if (s.isDirectory()) {
          // if it's a directory, that's good.
          // if the uid and gid aren't already set, then try to preserve
          // the ownership on up the tree.  Things in ~ remain owned by
          // the user, things in / remain owned by root, etc.
          if (uid === null && typeof s.uid === "number") foundUID = s.uid
          if (gid === null && typeof s.gid === "number") foundGID = s.gid

          // move onto next portion of path
          S(dirs.shift())

        } else {
          // the stat succeeded, but it's not a directory
          log.verbose(dir, "mkdir exists")
          log.silly(s, "stat("+dir+")")
          log.verbose(s.isDirectory(), "isDirectory()")
          cb(new Error("Failed to mkdir "+dir+": File exists"))
        }// if (isDirectory) else
      } // if (stat failed) else
    }) // stat

  // start the S function with the first item in the list of directories.
  })(dirs.shift())
}
<|endoftext|>


<commit_before>/*!
 * jquery.social.js
 *
 * @author Daniele De Nobili
 * @license MIT
 *
 * https://github.com/metaline/jquery-social
 */

/*jslint nomen: true, plusplus: true, passfail: true, browser: true, devel: true */
/*global jQuery */

(function ($) {
    "use strict";

    function loadScript(url, id) {
        var t = document.createElement('script'),
            s = document.getElementsByTagName('script')[0];

        if (id) {
            if (document.getElementById(id)) {
                return;
            }

            t.id = id;
        }

        t.type = 'text/javascript';
        t.async = true;
        t.src = url;

        s.parentNode.insertBefore(t, s);
    }

    function humanizeNumber(num) {
        if (num >= 1e6) {
            return (num / 1e6).toFixed(2) + 'M';
        }

        if (num >= 1e3) {
            return (num / 1e3).toFixed(1) + 'k';
        }

        return num;
    }

    function random() {
        var chars = 'abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789', r = [], i;

        for (i = 0; i < 8; i++) {
            r.push(chars[Math.floor(Math.random() * 60)]);
        }

        return r.join('');
    }

    function findAnchorTag(button) {
        var a;

        if (button.is('a')) {
            a = button;
        } else {
            a = button.find('a');

            if (a.length === 0) {
                button.children().wrapAll('');
                a = button.find('> a');
            }
        }
        return a;
    }

    var pluginName = "social",
        defaults = {
            template: {
                'facebook-share': '{total}',
                'twitter': 'Tweet',
                'googleplus': '{total}',
                'pinterest': '{total}',
                'linkedin': '{total}'
            },
            facebookAppId: '',
            lang: 'en_US',
            enableTracking: false,
            totalShareSelector: false
        },
        networks = {
            'facebook-share': {
                load: function (plugin) {
                    if (!plugin.options.facebookAppId) {
                        throw "Il tracking degli eventi di Facebook è possibile solo impostando l’opzione 'facebookAppId'";
                    }

                    if (window.fbAsyncInit) {
                        this.render(plugin);

                        return;
                    }

                    var self = this;

                    window.fbAsyncInit = function () {
                        window.FB.init({
                            appId: plugin.options.facebookAppId,
                            xfbml: true,
                            version: 'v2.5'
                        });

                        // Facebook Comment tracking
                        if (plugin.options.enableTracking['facebook-comment']) {
                            window.FB.Event.subscribe('comment.create', function (url) {
                                plugin.tracking('Facebook', 'Comment', url, plugin.options.enableTracking['facebook-comment']);
                            });
                        }

                        self.render(plugin);
                    };

                    loadScript(
                        '//connect.facebook.net/' + plugin.options.lang + '/sdk.js',
                        'facebook-jssdk'
                    );
                },
                onClick: function (plugin) {
                    window.FB.ui(
                        {
                            method: 'share',
                            href: plugin.url
                        },
                        function (response) {
                            if (response && !response.error_message && plugin.options.enableTracking['facebook-share']) {
                                plugin.tracking(
                                    'Facebook',
                                    'Share',
                                    plugin.url,
                                    plugin.options.enableTracking['facebook-share'],
                                    true,
                                    true
                                );
                            }
                        }
                    );
                },
                render: function (plugin) {
                    if (plugin.hasShareCount('facebook-share')) {
                        $.getJSON(
                            'https://graph.facebook.com/fql',
                            {
                                'q': 'SELECT like_count, total_count, share_count, comment_count FROM link_stat WHERE url = "' + plugin.url + '"'
                            }
                        ).done(function (response) {
                            var total = 0;

                            if (response.data && response.data[0] && response.data[0].total_count) {
                                total = response.data[0].total_count;
                            }

                            plugin.renderNetwork('facebook-share', total);
                        }).fail(function () {
                            plugin.renderNetwork('facebook-share', 0);
                        });
                    } else {
                        plugin.renderNetwork('facebook-share');
                    }
                }
            },
            googleplus: {
                load: function (plugin) {
                    if (plugin.hasShareCount('googleplus')) {

                        this.loadScript(function () {
                            // http://stackoverflow.com/questions/21524077/getting-google-1-page-shares-via-ajax-hidden-api
                            var params = {
                                nolog: true,
                                id: plugin.url,
                                source: "widget",
                                userId: "@viewer",
                                groupId: "@self"
                            };

                            window.gapi.client.rpcRequest('pos.plusones.get', 'v1', params).execute(function (resp) {
                                plugin.renderNetwork('googleplus', resp.result.metadata.globalCounts.count);
                            });
                        });
                    } else {
                        plugin.renderNetwork('googleplus');
                    }
                },
                onClick: function (plugin) {
                    window.open(
                        'https://plus.google.com/share?hl=' + this.fixLang(plugin.options.lang) + '&url=' + encodeURIComponent(plugin.url),
                        '',
                        'toolbar=0, status=0, width=900, height=500'
                    );

                    if (plugin.options.enableTracking.googleplus) {
                        plugin.tracking('Google', '+1', plugin.url, plugin.options.enableTracking.googleplus, true, false);
                    }
                },
                plusoneLoader: null,
                loaderPromise: null,
                loadScript: function (callback) {
                    if (this.loaderPromise === null) {
                        this.plusoneLoader = $.Deferred();
                        this.loaderPromise = $.when(this.plusoneLoader);
                    }

                    this.loaderPromise.done(callback);

                    window._onGooglePlusLoad = function () {
                        networks.googleplus.plusoneLoader.resolve();
                    };

                    loadScript('https://apis.google.com/js/client:plusone.js?onload=_onGooglePlusLoad');
                },
                fixLang: function (lang) {
                    switch (lang) {

                    case 'en_GB': // English (UK)
                    case 'en_US': // English (US)
                    case 'fr_CA': // French (Canada)
                    case 'pt_BR': // Portuguese (Brazil)
                    case 'pt_PT': // Portuguese (Portugal)"
                    case 'zh_CN': // Simplified Chinese (China)
                    case 'zh_HK': // Traditional Chinese (Hong Kong)
                    case 'zh_TW': // Traditional Chinese (Taiwan)
                        return lang.replace('_', '-');

                    case 'es_LA': // Spanish (Latin America)
                        return 'es-419';

                    case 'he_IL': // Hebrew
                        return 'iw';

                    case 'nn_NO': // Norwegian
                        return 'no';

                    case 'tl_PH': // Filipino
                        return 'fil';

                    }

                    return lang.substr(0, 2);
                }
            },
            twitter: {
                load: function (plugin) {
                    plugin.renderNetwork('twitter');

                    if (window.twttr) {
                        return;
                    }

                    // Twitter ha un codice un po' particolare per caricare le sue api
                    window.twttr = (function (d, s, id) {
                        var js, fjs = d.getElementsByTagName(s)[0],
                            t = window.twttr || {};

                        if (d.getElementById(id)) {
                            return t;
                        }

                        js = d.createElement(s);
                        js.id = id;
                        js.src = "https://platform.twitter.com/widgets.js";
                        fjs.parentNode.insertBefore(js, fjs);

                        t._e = [];
                        t.ready = function (f) {
                            t._e.push(f);
                        };

                        return t;
                    }(document, "script", "twitter-wjs"));

                    if (plugin.options.enableTracking.twitter) {
                        window.twttr.ready(function () {
                            window.twttr.events.bind('tweet', function (event) {
                                if (!event || event.type !== 'tweet') {
                                    return;
                                }

                                plugin.tracking(
                                    'Twitter',
                                    'Tweet',
                                    event.target.baseURI,
                                    plugin.options.enableTracking.twitter,
                                    true,
                                    true
                                );
                            });
                        });
                    }
                },
                onRender: function (plugin, button) {
                    var a = findAnchorTag(button),
                        url = 'https://twitter.com/intent/tweet?url=' + encodeURIComponent(plugin.url);

                    if (plugin.title) {
                        url += '&text=' + encodeURIComponent(plugin.title);
                    }

                    if (plugin.options.twitterVia) {
                        url += '&via=' + plugin.options.twitterVia;
                    }

                    a.attr('href', url);
                }
            },
            pinterest: {
                load: function (plugin) {
                    loadScript('//assets.pinterest.com/js/pinit.js');

                    if (plugin.hasShareCount('pinterest')) {
                        var f = '_PinterestCount' + random();

                        window[f] = function (data) {
                            plugin.renderNetwork('pinterest', data.count);
                        };

                        $.getScript('http://api.pinterest.com/v1/urls/count.json?url=' +
                            encodeURIComponent(plugin.url) + '&callback=' + f);
                    } else {
                        plugin.renderNetwork('pinterest');
                    }
                },
                onRender: function (plugin, button) {
                    var a = findAnchorTag(button), url;

                    url = 'https://www.pinterest.com/pin/create/button/?url=' + encodeURIComponent(plugin.url);

                    if (plugin.title) {
                        url += '&description=' + encodeURIComponent(plugin.title);
                    }

                    a.attr('href', url);
                    a.attr('data-pin-custom', true);
                    a.attr('data-pin-do', 'buttonPin');
                },
                onClick: function (plugin) {
                    if (window.PinUtils) {
                        window.PinUtils.pinAny();
                    }

                    if (plugin.options.enableTracking.pinterest) {
                        plugin.tracking('Pinterest', 'Pin It', plugin.url, plugin.options.enableTracking.pinterest, true, true);
                    }
                }
            },
            linkedin: {
                load: function (plugin) {
                    if (plugin.hasShareCount('linkedin')) {
                        var f = '_linkedInCount' + random();

                        window[f] = function (data) {
                            plugin.renderNetwork('linkedin', data.count);
                        };

                        $.getScript('https://www.linkedin.com/countserv/count/share?url=' +
                            encodeURIComponent(plugin.url) + '&format=jsonp&callback=' + f);
                    } else {
                        plugin.renderNetwork('linkedin');
                    }
                },
                onClick: function (plugin) {
                    var url = 'https://www.linkedin.com/shareArticle?mini=true&url=' + encodeURIComponent(plugin.url);

                    if (plugin.title) {
                        url += '&title=' + encodeURIComponent(plugin.title);
                    }

                    if (plugin.text) {
                        url += '&summary=' + encodeURIComponent(plugin.text);
                    }

                    window.open(
                        url,
                        'linkedin',
                        'toolbar=no,width=550,height=550'
                    );

                    if (plugin.options.enableTracking.linkedin) {
                        plugin.tracking('LinkedIn', 'Share', plugin.url, plugin.options.enableTracking.linkedin, true, true);
                    }
                }
            }
        };

    function Plugin(element, options) {
        this.element = $(element);
        this.options = $.extend({}, defaults, options);

        this.init();
    }

    Plugin.prototype = {
        init: function () {
            var plugin = this,
                networksLength = 0;

            this.networkButtons = {};

            this.element.find('[data-network]').each(function () {
                var button = $(this),
                    name = button.data('network');

                plugin.networkButtons[name] = button;

                networksLength++;
            });

            if (!networksLength) {
                return;
            }

            this.url = this.element.data('url') || $('meta[property="og:url"]').attr('content') || document.location.href;
            this.title = this.element.data('title') || $('meta[property="og:title"]').attr('content') || document.title;
            this.text = this.element.data('text') || $('meta[property="og:description"]').attr('content') || '';

            this.initTotal();
            this.load();
        },

        load: function () {
            var plugin = this;

            $.each(this.networkButtons, function (name) {
                if (networks[name]) {
                    networks[name].load(plugin);
                }
            });
        },

        renderNetwork: function (network, total) {
            var plugin = this,
                button = this.networkButtons[network];

            button.data('share', total);

            if (networks[network]) {
                plugin.renderButton(network, total);

                if (networks[network] && typeof networks[network].onRender === 'function') {
                    networks[network].onRender(plugin, button);
                }

                button.on('click', function (event) {
                    event.preventDefault();

                    button.data('share', button.data('share') + 1);

                    plugin.renderButton(network, button.data('share'));

                    if (typeof networks[network].onClick === 'function') {
                        networks[network].onClick(plugin, button);
                    }
                });
            }
        },

        renderButton: function (network, total) {
            this.networkButtons[network].html(
                this.options.template[network].replace('{total}', humanizeNumber(total))
            );

            this.incrementTotal(total);
        },

        hasShareCount: function (network) {
            return this.options.template[network].indexOf('{total}') !== -1;
        },

        tracking: function (network, event, url, value, e, s) {
            if (window.ga) {
                if (e === undefined || e) {
                    // https://developers.google.com/analytics/devguides/collection/analyticsjs/events
                    window.ga('send', 'event', 'Social', event + ' (' + network + ')', url, value);
                }

                if (s === undefined || s) {
                    // https://developers.google.com/analytics/devguides/collection/analyticsjs/social-interactions
                    window.ga('send', 'social', network, event, url, value);
                }
            }
        },

        initTotal: function () {
            if (this.options.totalShareSelector) {
                this.$totalShare = $(this.options.totalShareSelector);
            }

            if (!this.$totalShare) {
                return;
            }

            this.total = 0;
            this.$totalShare.text(this.total);
        },

        incrementTotal: function (total) {
            if (!this.$totalShare || !total) {
                return;
            }

            this.total += total;
            this.$totalShare.text(humanizeNumber(this.total));
        }
    };

    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin(this, options));
            }
        });
    };

}(jQuery));
<commit_msg>Standardize humanizeNumber function.<commit_after>/*!
 * jquery.social.js
 *
 * @author Daniele De Nobili
 * @license MIT
 *
 * https://github.com/metaline/jquery-social
 */

/*jslint nomen: true, plusplus: true, passfail: true, browser: true, devel: true */
/*global jQuery */

(function ($) {
    "use strict";

    function loadScript(url, id) {
        var t = document.createElement('script'),
            s = document.getElementsByTagName('script')[0];

        if (id) {
            if (document.getElementById(id)) {
                return;
            }

            t.id = id;
        }

        t.type = 'text/javascript';
        t.async = true;
        t.src = url;

        s.parentNode.insertBefore(t, s);
    }

    function humanizeNumber(num) {
        if (num >= 1e6) {
            return (num / 1e6).toFixed(1) + 'M';
        }

        if (num >= 1e3) {
            return (num / 1e3).toFixed(1) + 'k';
        }

        return num;
    }

    function random() {
        var chars = 'abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789', r = [], i;

        for (i = 0; i < 8; i++) {
            r.push(chars[Math.floor(Math.random() * 60)]);
        }

        return r.join('');
    }

    function findAnchorTag(button) {
        var a;

        if (button.is('a')) {
            a = button;
        } else {
            a = button.find('a');

            if (a.length === 0) {
                button.children().wrapAll('');
                a = button.find('> a');
            }
        }
        return a;
    }

    var pluginName = "social",
        defaults = {
            template: {
                'facebook-share': '{total}',
                'twitter': 'Tweet',
                'googleplus': '{total}',
                'pinterest': '{total}',
                'linkedin': '{total}'
            },
            facebookAppId: '',
            lang: 'en_US',
            enableTracking: false,
            totalShareSelector: false
        },
        networks = {
            'facebook-share': {
                load: function (plugin) {
                    if (!plugin.options.facebookAppId) {
                        throw "Il tracking degli eventi di Facebook è possibile solo impostando l’opzione 'facebookAppId'";
                    }

                    if (window.fbAsyncInit) {
                        this.render(plugin);

                        return;
                    }

                    var self = this;

                    window.fbAsyncInit = function () {
                        window.FB.init({
                            appId: plugin.options.facebookAppId,
                            xfbml: true,
                            version: 'v2.5'
                        });

                        // Facebook Comment tracking
                        if (plugin.options.enableTracking['facebook-comment']) {
                            window.FB.Event.subscribe('comment.create', function (url) {
                                plugin.tracking('Facebook', 'Comment', url, plugin.options.enableTracking['facebook-comment']);
                            });
                        }

                        self.render(plugin);
                    };

                    loadScript(
                        '//connect.facebook.net/' + plugin.options.lang + '/sdk.js',
                        'facebook-jssdk'
                    );
                },
                onClick: function (plugin) {
                    window.FB.ui(
                        {
                            method: 'share',
                            href: plugin.url
                        },
                        function (response) {
                            if (response && !response.error_message && plugin.options.enableTracking['facebook-share']) {
                                plugin.tracking(
                                    'Facebook',
                                    'Share',
                                    plugin.url,
                                    plugin.options.enableTracking['facebook-share'],
                                    true,
                                    true
                                );
                            }
                        }
                    );
                },
                render: function (plugin) {
                    if (plugin.hasShareCount('facebook-share')) {
                        $.getJSON(
                            'https://graph.facebook.com/fql',
                            {
                                'q': 'SELECT like_count, total_count, share_count, comment_count FROM link_stat WHERE url = "' + plugin.url + '"'
                            }
                        ).done(function (response) {
                            var total = 0;

                            if (response.data && response.data[0] && response.data[0].total_count) {
                                total = response.data[0].total_count;
                            }

                            plugin.renderNetwork('facebook-share', total);
                        }).fail(function () {
                            plugin.renderNetwork('facebook-share', 0);
                        });
                    } else {
                        plugin.renderNetwork('facebook-share');
                    }
                }
            },
            googleplus: {
                load: function (plugin) {
                    if (plugin.hasShareCount('googleplus')) {

                        this.loadScript(function () {
                            // http://stackoverflow.com/questions/21524077/getting-google-1-page-shares-via-ajax-hidden-api
                            var params = {
                                nolog: true,
                                id: plugin.url,
                                source: "widget",
                                userId: "@viewer",
                                groupId: "@self"
                            };

                            window.gapi.client.rpcRequest('pos.plusones.get', 'v1', params).execute(function (resp) {
                                plugin.renderNetwork('googleplus', resp.result.metadata.globalCounts.count);
                            });
                        });
                    } else {
                        plugin.renderNetwork('googleplus');
                    }
                },
                onClick: function (plugin) {
                    window.open(
                        'https://plus.google.com/share?hl=' + this.fixLang(plugin.options.lang) + '&url=' + encodeURIComponent(plugin.url),
                        '',
                        'toolbar=0, status=0, width=900, height=500'
                    );

                    if (plugin.options.enableTracking.googleplus) {
                        plugin.tracking('Google', '+1', plugin.url, plugin.options.enableTracking.googleplus, true, false);
                    }
                },
                plusoneLoader: null,
                loaderPromise: null,
                loadScript: function (callback) {
                    if (this.loaderPromise === null) {
                        this.plusoneLoader = $.Deferred();
                        this.loaderPromise = $.when(this.plusoneLoader);
                    }

                    this.loaderPromise.done(callback);

                    window._onGooglePlusLoad = function () {
                        networks.googleplus.plusoneLoader.resolve();
                    };

                    loadScript('https://apis.google.com/js/client:plusone.js?onload=_onGooglePlusLoad');
                },
                fixLang: function (lang) {
                    switch (lang) {

                    case 'en_GB': // English (UK)
                    case 'en_US': // English (US)
                    case 'fr_CA': // French (Canada)
                    case 'pt_BR': // Portuguese (Brazil)
                    case 'pt_PT': // Portuguese (Portugal)"
                    case 'zh_CN': // Simplified Chinese (China)
                    case 'zh_HK': // Traditional Chinese (Hong Kong)
                    case 'zh_TW': // Traditional Chinese (Taiwan)
                        return lang.replace('_', '-');

                    case 'es_LA': // Spanish (Latin America)
                        return 'es-419';

                    case 'he_IL': // Hebrew
                        return 'iw';

                    case 'nn_NO': // Norwegian
                        return 'no';

                    case 'tl_PH': // Filipino
                        return 'fil';

                    }

                    return lang.substr(0, 2);
                }
            },
            twitter: {
                load: function (plugin) {
                    plugin.renderNetwork('twitter');

                    if (window.twttr) {
                        return;
                    }

                    // Twitter ha un codice un po' particolare per caricare le sue api
                    window.twttr = (function (d, s, id) {
                        var js, fjs = d.getElementsByTagName(s)[0],
                            t = window.twttr || {};

                        if (d.getElementById(id)) {
                            return t;
                        }

                        js = d.createElement(s);
                        js.id = id;
                        js.src = "https://platform.twitter.com/widgets.js";
                        fjs.parentNode.insertBefore(js, fjs);

                        t._e = [];
                        t.ready = function (f) {
                            t._e.push(f);
                        };

                        return t;
                    }(document, "script", "twitter-wjs"));

                    if (plugin.options.enableTracking.twitter) {
                        window.twttr.ready(function () {
                            window.twttr.events.bind('tweet', function (event) {
                                if (!event || event.type !== 'tweet') {
                                    return;
                                }

                                plugin.tracking(
                                    'Twitter',
                                    'Tweet',
                                    event.target.baseURI,
                                    plugin.options.enableTracking.twitter,
                                    true,
                                    true
                                );
                            });
                        });
                    }
                },
                onRender: function (plugin, button) {
                    var a = findAnchorTag(button),
                        url = 'https://twitter.com/intent/tweet?url=' + encodeURIComponent(plugin.url);

                    if (plugin.title) {
                        url += '&text=' + encodeURIComponent(plugin.title);
                    }

                    if (plugin.options.twitterVia) {
                        url += '&via=' + plugin.options.twitterVia;
                    }

                    a.attr('href', url);
                }
            },
            pinterest: {
                load: function (plugin) {
                    loadScript('//assets.pinterest.com/js/pinit.js');

                    if (plugin.hasShareCount('pinterest')) {
                        var f = '_PinterestCount' + random();

                        window[f] = function (data) {
                            plugin.renderNetwork('pinterest', data.count);
                        };

                        $.getScript('http://api.pinterest.com/v1/urls/count.json?url=' +
                            encodeURIComponent(plugin.url) + '&callback=' + f);
                    } else {
                        plugin.renderNetwork('pinterest');
                    }
                },
                onRender: function (plugin, button) {
                    var a = findAnchorTag(button), url;

                    url = 'https://www.pinterest.com/pin/create/button/?url=' + encodeURIComponent(plugin.url);

                    if (plugin.title) {
                        url += '&description=' + encodeURIComponent(plugin.title);
                    }

                    a.attr('href', url);
                    a.attr('data-pin-custom', true);
                    a.attr('data-pin-do', 'buttonPin');
                },
                onClick: function (plugin) {
                    if (window.PinUtils) {
                        window.PinUtils.pinAny();
                    }

                    if (plugin.options.enableTracking.pinterest) {
                        plugin.tracking('Pinterest', 'Pin It', plugin.url, plugin.options.enableTracking.pinterest, true, true);
                    }
                }
            },
            linkedin: {
                load: function (plugin) {
                    if (plugin.hasShareCount('linkedin')) {
                        var f = '_linkedInCount' + random();

                        window[f] = function (data) {
                            plugin.renderNetwork('linkedin', data.count);
                        };

                        $.getScript('https://www.linkedin.com/countserv/count/share?url=' +
                            encodeURIComponent(plugin.url) + '&format=jsonp&callback=' + f);
                    } else {
                        plugin.renderNetwork('linkedin');
                    }
                },
                onClick: function (plugin) {
                    var url = 'https://www.linkedin.com/shareArticle?mini=true&url=' + encodeURIComponent(plugin.url);

                    if (plugin.title) {
                        url += '&title=' + encodeURIComponent(plugin.title);
                    }

                    if (plugin.text) {
                        url += '&summary=' + encodeURIComponent(plugin.text);
                    }

                    window.open(
                        url,
                        'linkedin',
                        'toolbar=no,width=550,height=550'
                    );

                    if (plugin.options.enableTracking.linkedin) {
                        plugin.tracking('LinkedIn', 'Share', plugin.url, plugin.options.enableTracking.linkedin, true, true);
                    }
                }
            }
        };

    function Plugin(element, options) {
        this.element = $(element);
        this.options = $.extend({}, defaults, options);

        this.init();
    }

    Plugin.prototype = {
        init: function () {
            var plugin = this,
                networksLength = 0;

            this.networkButtons = {};

            this.element.find('[data-network]').each(function () {
                var button = $(this),
                    name = button.data('network');

                plugin.networkButtons[name] = button;

                networksLength++;
            });

            if (!networksLength) {
                return;
            }

            this.url = this.element.data('url') || $('meta[property="og:url"]').attr('content') || document.location.href;
            this.title = this.element.data('title') || $('meta[property="og:title"]').attr('content') || document.title;
            this.text = this.element.data('text') || $('meta[property="og:description"]').attr('content') || '';

            this.initTotal();
            this.load();
        },

        load: function () {
            var plugin = this;

            $.each(this.networkButtons, function (name) {
                if (networks[name]) {
                    networks[name].load(plugin);
                }
            });
        },

        renderNetwork: function (network, total) {
            var plugin = this,
                button = this.networkButtons[network];

            button.data('share', total);

            if (networks[network]) {
                plugin.renderButton(network, total);

                if (networks[network] && typeof networks[network].onRender === 'function') {
                    networks[network].onRender(plugin, button);
                }

                button.on('click', function (event) {
                    event.preventDefault();

                    button.data('share', button.data('share') + 1);

                    plugin.renderButton(network, button.data('share'));

                    if (typeof networks[network].onClick === 'function') {
                        networks[network].onClick(plugin, button);
                    }
                });
            }
        },

        renderButton: function (network, total) {
            this.networkButtons[network].html(
                this.options.template[network].replace('{total}', humanizeNumber(total))
            );

            this.incrementTotal(total);
        },

        hasShareCount: function (network) {
            return this.options.template[network].indexOf('{total}') !== -1;
        },

        tracking: function (network, event, url, value, e, s) {
            if (window.ga) {
                if (e === undefined || e) {
                    // https://developers.google.com/analytics/devguides/collection/analyticsjs/events
                    window.ga('send', 'event', 'Social', event + ' (' + network + ')', url, value);
                }

                if (s === undefined || s) {
                    // https://developers.google.com/analytics/devguides/collection/analyticsjs/social-interactions
                    window.ga('send', 'social', network, event, url, value);
                }
            }
        },

        initTotal: function () {
            if (this.options.totalShareSelector) {
                this.$totalShare = $(this.options.totalShareSelector);
            }

            if (!this.$totalShare) {
                return;
            }

            this.total = 0;
            this.$totalShare.text(this.total);
        },

        incrementTotal: function (total) {
            if (!this.$totalShare || !total) {
                return;
            }

            this.total += total;
            this.$totalShare.text(humanizeNumber(this.total));
        }
    };

    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin(this, options));
            }
        });
    };

}(jQuery));
<|endoftext|>