<commit_before>//     Polynar.js 1.0
//     http://srv2.blobtech.nl/Polynar
//     (c) 2014 Pablo Kebees
//     Polynar may be freely distributed under the MIT license.

( function() {

	// the name of the Polynar object
	var objName = 'Polynar';

	// the Polynar object
	var obj = {};

	// registering useful character sets
	obj.numeric = '0123456789';
	obj.hex = obj.numeric + 'ABCDEF';
	obj.alphaLower = 'abcdefghijklmnopqrstuvwxyz';
	obj.alphaUpper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	obj.alpha = obj.alphaLower + obj.alphaUpper;
	obj.alphanumeric = obj.numeric + obj.alpha;
	obj.printable = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
	obj.Base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

	// the default character set to use
	var defaultCharset = obj.Base64;

	// registering our object name, both browser and server side
	if( typeof exports == 'undefined' )
		this[ objName ] = obj;
	else {

		if ( typeof module !== 'undefined' && module.exports )
			exports = module.exports = obj;

		exports[ objName ] = obj;

	}

	// define our own is[type] functions
	var isArray = function( obj ) { return toString.call( obj ) === '[object Array]'; };
	var isObject = function( obj ) { return toString.call( obj ) === '[object Object]'; };

	// validate encodingOptions
	var validateOptions = function( options ) {

		if( typeof options == 'undefined' )
			throw TypeError( 'Undefined encoding options' );

		if( !isObject( options ) )
			throw TypeError( options + ' is not an object' );

		switch( options.type ) {

			case 'number':

				// no precision by default
				if( typeof options.precision == 'undefined' )
					options.precision = 1;
				else if( typeof options.precision != 'number' )
					throw TypeError( 'Invalid precision' );

				// 1 step by default
				if( typeof options.step == 'undefined' )
					options.step = 1;
				else if( typeof options.step != 'number' || options.step < 0 )
					throw TypeError( 'Invalid step size' );

				// if offset defined then set the upper bound regardless of sign
				if( typeof options.offset != 'undefined' ) {
					options.min = 0;
					options.max = options.offset;
				}

				// both bounds must be integer
				if(
					typeof options.min != 'number' ||
					typeof options.max != 'number' ||
					options.min % 1 != 0 ||
					options.max % 1 != 0
				)
					throw TypeError( 'Invalid range bound' );

				// swap bounds if wrong order
				if( options.min > options.max )
					options.min = options.max + ( options.max = options.min, 0 );

				if( ( options.max - options.min ) / options.step % 1 > 0.0000000000000001 ) // fucking floats
					throw TypeError( 'Range bound outside step range' );

				break;

			case 'string':

				if( typeof options.max != 'number' || options.max % 1 != 0 || options.max < 0 )
					throw TypeError( 'Invalid string limit' );

				options.charset = validateCharset( options.charset );

				break;

			case 'item':

				if(
					typeof options.list == 'undefined' ||
					!isArray( options.list ) ||
					options.list.length == 0
				)
					throw TypeError( 'Invalid or empty list' );

				if( typeof options.sort == 'bool' && options.sort === true )
					options.list = options.list.slice( 0 ).sort(); // slice, so we don't alter the original array

				break;

			case 'boolean':

				break;

			case 'object':

				if(
					typeof options.template == 'undefined' ||
					options.template.toString() != '[object Object]'
				)
					throw TypeError( 'Invalid object template' );

				break;

			default:

				throw TypeError( 'Invalid encoding type' );

		}

		if( typeof options.limit != 'undefined' )
			if( typeof options.limit != 'number' || options.limit % 1 != 0 || options.limit < 0 )
				throw TypeError( 'Invalid item limit' );

		return options;

	}

	// validate character set
	var validateCharset = function( charset ) {

		var errChar = 'Invalid character set', errBin = 'Invalid binary range';

		if( typeof charset == 'undefined' )
			charset = defaultCharset;
		else if( typeof charset == 'number' ) {

			if( charset % 1 != 0 || charset < 2 )
				throw TypeError( errBin );

			charset = [ 0, charset ];

		} else if( typeof charset == 'string' ) {

			if( charset.match( /(.).*\1/ ) )
				throw Error( errChar );

		} else if( isArray( charset ) ) {

			if( charset.length != 2 )
				throw TypeError( errBin );

			// swap bounds if wrong order
			if( charset[ 0 ] > charset[ 1 ] )
				charset.reverse();

		} else
			throw TypeError( errChar );

		return charset;

	}

	// our encoder class
	obj.encoder = function() {

		if( !this instanceof obj.encoder )
			return new obj.encoder();

		this.radii = new Array();
		this.integers = new Array();

	}

	obj.encoder.prototype.write = function( items, options ) {

		var i, pos, chr, size, tempInt, workTpl;

		options = validateOptions( options );

		if( !isArray( items ) )
			items = [ items ];

		if( options.limit )
			if( items.length > options.limit )
				throw RangeError( 'Item count exceeds limit' );
			else
				this.compose( items.length, options.limit + 1 );

		if( options.type == 'string' && typeof options.charset == 'string' )
			size = options.charset[ 1 ] - options.charset[ 0 ] + 1;

		for( i in items )
			if( options.type == 'item' ) {

				pos = options.list.indexOf( items[ i ] );

				if( pos == -1 )
					throw Error( 'Item \'' + items[ i ] + '\' not found in list' );

				this.compose( pos, options.list.length );

			} else if( options.type == 'number' ) {

				if( typeof items[ i ] != 'number' )
					throw TypeError( 'Item \'' + items[ i ] + '\' not a number' );

				if( items[ i ] < options.min || items[ i ] > options.max )
					throw RangeError( 'Item \'' + items[ i ] + '\' exceeds range bounds' );

				tempInt = ( items[ i ] - options.min ) / options.step;

				if( tempInt % 1 > 0.0000000000000001 ) // fucking floats
					throw RangeError( 'Item \'' + items[ i ] + '\' outside step range' );

				this.compose( ~~tempInt, ( options.max - options.min ) / options.step + 1 );

			} else if( options.type == 'boolean' ) {

				if( typeof items[ i ] != 'boolean' )
					throw TypeError( 'Item \'' + items[ i ] + '\' not boolean' );

				this.compose( +items[ i ], 2 );

			} else if( options.type == 'string' ) {

				if( typeof items[ i ] != 'string' )
					throw TypeError( 'Item \'' + items[ i ] + '\' not string' );

				if( items[ i ].length > options.max )
					throw RangeError( 'Item \'' + items[ i ] + '\' exceeds max length' );

				this.compose( items[ i ].length, options.max );

				for( chr = 0; chr < items[ i ].length; chr ++ )
					if( typeof options.charset == 'string' ) {

						pos = options.charset.indexOf( items[ i ].charAt( chr ) );

						if( pos == -1 )
							throw Error( 'String not compliant with character set' );

						this.compose( pos, options.charset.length );

					} else {

						pos = items[ i ].charCodeAt( chr );

						if( pos < options.charset[ 0 ] || pos > options.charset[ 1 ] )
							throw Error( 'String not compliant with character set' );

						this.compose( pos - options.charset[ 0 ], size );

					}

				this.write( items[ i ].split( '' ), { type: 'item', list: options.charset, limit: options.max } );

			} else if( options.type == 'object' ) {

				workTpl = function( obj, tpl ) {

					if( options.sort )
						var keys = Object.keys( tpl ).sort();
					else
						var keys = tpl;

					for( var key in keys ) {

						if( typeof obj[ key ] == 'undefined' )
							throw ReferenceError( 'Object has no property \'' + key + '\'' );

						if( typeof tpl[ key ].type == 'string' )
							this.write( obj[ key ], tpl[ key ] );
						else if( isObject( tpl[ key ] ) )
							workTpl( obj[ key ], tpl[ key ] );
						else
							throw TypeError( 'Invalid object template' );

					}
				}

				workTpl.call( this, items[ i ], options.template );

			}

	}

	obj.encoder.prototype.compose = function( integer, radix ) {

		this.integers.push( integer );
		this.radii.push( radix );

	}

	obj.encoder.prototype.toString = function( charset ) {

		var binary = false;

		charset = validateCharset( charset );

		if( typeof charset == 'string' )
			var size = charset.length;
		else
			var size = charset[ 1 ] - charset[ 0 ] + 1;

		var radii = 1;
		var current = 0;

		var build = function( integer, radix ) {

			var left = Math.floor( size / radii );

			if( left < 2 ) {

				if( typeof charset == 'string' )
					str += charset.charAt( current );
				else
					str += String.fromCharCode( current + charset[ 0 ] );

				current = 0;
				radii = 1;
				left = size;

			}

			if( left >= radix ) {

				current += radii * integer;
				radii *= radix;

			} else {

				var factor = Math.ceil( radix / left );

				current += radii * Math.floor( integer / factor );
				radii *= left;

				build( integer % factor, factor );

			}

		}

		var str = '';
		for( var i in this.radii )
			build( this.integers[ i ], this.radii[ i ] );

		if( radii != 0 )
			if( typeof charset == 'string' )
				str += charset.charAt( current );
			else
				str += String.fromCharCode( current + charset[ 0 ] );

		return str;

	}

	// our decoder class
	obj.decoder = function( str, charset ) {

		if( !this instanceof obj.decoder )
			return new obj.decoder( str, charset );

		if( typeof str == 'undefined' )
			throw Error( 'Missing first argument' );

		str = str.toString();

		charset = validateCharset( charset );

		if( typeof charset == 'string' )
			this.size = charset.length;
		else
			this.size = charset[ 1 ] - charset[ 0 ] + 1;

		this.str = str;
		this.charset = charset;
		this._next();

	}

	obj.decoder.prototype._next = function() {

		if( typeof this.current == 'undefined' )
			this.pointer = 0;
		 else
			this.pointer ++;

		if( this.pointer == this.str.length )
			throw new Error( 'Unexpected EOD while parsing' );

		this.radii = 1;

		if( typeof this.charset == 'string' ) {

			this.current = this.charset.indexOf( this.str.charAt( this.pointer ) );

			if( this.current == -1 )
				throw Error( 'Byte at ' + this.pointer + ' not found in character set' );

		} else {

			this.current = this.str.charCodeAt( this.pointer ) - this.charset[ 0 ];

			if( this.current > this.charset )
				throw Error( 'Byte at ' + this.pointer + ' does not fit binary range' );

		}

	}

	obj.decoder.prototype.parse = function( radix ) {

		var left = Math.floor( this.size / this.radii );

		if( left == 1 ) {

			if( this.current != 0 )
				throw Error( 'Oversaturated byte at byte ' + this.pointer );

			this._next();
			left = this.size;

		}

		if( left >= radix ) {

			var integer = this.current % radix;
			this.current = Math.floor( this.current / radix );
			this.radii *= radix;

		} else {

			var factor = Math.ceil( radix / left );

			var integer = this.current * factor;
			this.current = Math.floor( this.current / left );
			this.radii *= left;

			integer += this.parse( factor );

		}

		return integer;

	}

	obj.decoder.prototype.read = function( options, count ) {

		var i, obj, chr, size, len, str;

		if( typeof count == 'undefined' )
			var count = 1;
		else if( typeof count != 'number' || count % 1 != 0 || count < 0 )
			throw TypeError( 'Count must be positive integer' );

		options = validateOptions( options );

		if( options.limit )
			count = this.parse( options.limit + 1 );

		if( options.type == 'string' && typeof options.charset == 'string' )
			size = options.charset[ 1 ] - options.charset[ 0 ] + 1;

		var items = new Array();

		for( i = 0; i < count; i++ )
			if( options.type == 'item' ) {

				items.push( options.list[ this.parse( options.list.length ) ] );

			} else if( options.type == 'number' ) {

				items.push( this.parse( ( options.max - options.min ) / options.step + 1 ) * options.step + options.min );

			} else if( options.type == 'boolean' ) {

				items.push( new Boolean( this.parse( 2 ) ) );

			} else if( options.type == 'string' ) {

				len = this.parse( options.max );
				str = '';

				for( chr = 0; chr < len; chr ++ )
					if( typeof options.charset == 'string' )
						str += options.charset.charAt( this.parse( options.charset.length ) );
					else
						str += this.parse( size ) + options.charset[ 0 ];

				items.push( str );

			} else if( options.type == 'object' ) {

				if( typeof options.base == 'function' )
					base = options.base();
				else
					base = options.base;

				if( typeof options.base == 'undefined' || typeof options.base != 'object' )
					base = {};

				workTpl = function( obj, tpl ) {

					if( options.sort )
						var keys = Object.keys( tpl );
					else
						var keys = tpl;

					for( var key in keys ) {

						if( typeof tpl[ key ].type == 'string' )
							obj[ key ] = this.read( tpl[ key ] );
						else if( isObject( tpl[ key ] ) ) {

							if( typeof obj[ key ] == 'undefined' )
								obj[ key ] = {};

							workTpl( obj[ key ], tpl[ key ] );

						} else
							throw TypeError( 'Invalid object template' );

					}
				}

				workTpl.call( this, base, options.template )
				items.push( base );

			}

		if( count == 1 )
			items = items.pop();

		return items;

	}

} ).call( this );<commit_msg>Fixed strings<commit_after>//     Polynar.js 1.0
//     http://srv2.blobtech.nl/Polynar
//     (c) 2014 Pablo Kebees
//     Polynar may be freely distributed under the MIT license.

( function() {

	// the name of the Polynar object
	var objName = 'Polynar';

	// the Polynar object
	var obj = {};

	// registering useful character sets
	obj.numeric = '0123456789';
	obj.hex = obj.numeric + 'ABCDEF';
	obj.alphaLower = 'abcdefghijklmnopqrstuvwxyz';
	obj.alphaUpper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	obj.alpha = obj.alphaLower + obj.alphaUpper;
	obj.alphanumeric = obj.numeric + obj.alpha;
	obj.printable = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
	obj.Base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

	// the default character set to use
	var defaultCharset = obj.Base64;

	// registering our object name, both browser and server side
	if( typeof exports == 'undefined' )
		this[ objName ] = obj;
	else {

		if ( typeof module !== 'undefined' && module.exports )
			exports = module.exports = obj;

		exports[ objName ] = obj;

	}

	// define our own is[type] functions
	var isArray = function( obj ) { return toString.call( obj ) === '[object Array]'; };
	var isObject = function( obj ) { return toString.call( obj ) === '[object Object]'; };

	// validate encodingOptions
	var validateOptions = function( options ) {

		if( typeof options == 'undefined' )
			throw TypeError( 'Undefined encoding options' );

		if( !isObject( options ) )
			throw TypeError( options + ' is not an object' );

		switch( options.type ) {

			case 'number':

				// no precision by default
				if( typeof options.precision == 'undefined' )
					options.precision = 1;
				else if( typeof options.precision != 'number' )
					throw TypeError( 'Invalid precision' );

				// 1 step by default
				if( typeof options.step == 'undefined' )
					options.step = 1;
				else if( typeof options.step != 'number' || options.step < 0 )
					throw TypeError( 'Invalid step size' );

				// if offset defined then set the upper bound regardless of sign
				if( typeof options.offset != 'undefined' ) {
					options.min = 0;
					options.max = options.offset;
				}

				// both bounds must be integer
				if(
					typeof options.min != 'number' ||
					typeof options.max != 'number' ||
					options.min % 1 != 0 ||
					options.max % 1 != 0
				)
					throw TypeError( 'Invalid range bound' );

				// swap bounds if wrong order
				if( options.min > options.max )
					options.min = options.max + ( options.max = options.min, 0 );

				if( ( options.max - options.min ) / options.step % 1 > 0.0000000000000001 ) // fucking floats
					throw TypeError( 'Range bound outside step range' );

				break;

			case 'string':

				if( typeof options.max != 'number' || options.max % 1 != 0 || options.max < 0 )
					throw TypeError( 'Invalid string limit' );

				options.charset = validateCharset( options.charset );

				break;

			case 'item':

				if(
					typeof options.list == 'undefined' ||
					!isArray( options.list ) ||
					options.list.length == 0
				)
					throw TypeError( 'Invalid or empty list' );

				if( typeof options.sort == 'bool' && options.sort === true )
					options.list = options.list.slice( 0 ).sort(); // slice, so we don't alter the original array

				break;

			case 'boolean':

				break;

			case 'object':

				if(
					typeof options.template == 'undefined' ||
					options.template.toString() != '[object Object]'
				)
					throw TypeError( 'Invalid object template' );

				break;

			default:

				throw TypeError( 'Invalid encoding type' );

		}

		if( typeof options.limit != 'undefined' )
			if( typeof options.limit != 'number' || options.limit % 1 != 0 || options.limit < 0 )
				throw TypeError( 'Invalid item limit' );

		return options;

	}

	// validate character set
	var validateCharset = function( charset ) {

		var errChar = 'Invalid character set', errBin = 'Invalid binary range';

		if( typeof charset == 'undefined' )
			charset = defaultCharset;
		else if( typeof charset == 'number' ) {

			if( charset % 1 != 0 || charset < 2 )
				throw TypeError( errBin );

			charset = [ 0, charset ];

		} else if( typeof charset == 'string' ) {

			if( charset.match( /(.).*\1/ ) )
				throw Error( errChar );

		} else if( isArray( charset ) ) {

			if( charset.length != 2 )
				throw TypeError( errBin );

			// swap bounds if wrong order
			if( charset[ 0 ] > charset[ 1 ] )
				charset.reverse();

		} else
			throw TypeError( errChar );

		return charset;

	}

	// our encoder class
	obj.encoder = function() {

		if( !this instanceof obj.encoder )
			return new obj.encoder();

		this.radii = new Array();
		this.integers = new Array();

	}

	obj.encoder.prototype.write = function( items, options ) {

		var i, pos, chr, size, tempInt, workTpl;

		options = validateOptions( options );

		if( !isArray( items ) )
			items = [ items ];

		if( options.limit )
			if( items.length > options.limit )
				throw RangeError( 'Item count exceeds limit' );
			else
				this.compose( items.length, options.limit + 1 );

		if( options.type == 'string' && typeof options.charset == 'string' )
			size = options.charset[ 1 ] - options.charset[ 0 ] + 1;

		for( i in items )
			if( options.type == 'item' ) {

				pos = options.list.indexOf( items[ i ] );

				if( pos == -1 )
					throw Error( 'Item \'' + items[ i ] + '\' not found in list' );

				this.compose( pos, options.list.length );

			} else if( options.type == 'number' ) {

				if( typeof items[ i ] != 'number' )
					throw TypeError( 'Item \'' + items[ i ] + '\' not a number' );

				if( items[ i ] < options.min || items[ i ] > options.max )
					throw RangeError( 'Item \'' + items[ i ] + '\' exceeds range bounds' );

				tempInt = ( items[ i ] - options.min ) / options.step;

				if( tempInt % 1 > 0.0000000000000001 ) // fucking floats
					throw RangeError( 'Item \'' + items[ i ] + '\' outside step range' );

				this.compose( ~~tempInt, ( options.max - options.min ) / options.step + 1 );

			} else if( options.type == 'boolean' ) {

				if( typeof items[ i ] != 'boolean' )
					throw TypeError( 'Item \'' + items[ i ] + '\' not boolean' );

				this.compose( +items[ i ], 2 );

			} else if( options.type == 'string' ) {

				if( typeof items[ i ] != 'string' )
					throw TypeError( 'Item \'' + items[ i ] + '\' not string' );

				if( items[ i ].length > options.max )
					throw RangeError( 'Item \'' + items[ i ] + '\' exceeds max length' );

				this.compose( items[ i ].length, options.max );

				for( chr = 0; chr < items[ i ].length; chr ++ )
					if( typeof options.charset == 'string' ) {

						pos = options.charset.indexOf( items[ i ].charAt( chr ) );

						if( pos == -1 )
							throw Error( 'String not compliant with character set' );

						this.compose( pos, options.charset.length );

					} else {

						pos = items[ i ].charCodeAt( chr );

						if( pos < options.charset[ 0 ] || pos > options.charset[ 1 ] )
							throw Error( 'String not compliant with character set' );

						this.compose( pos - options.charset[ 0 ], size );

					}

			} else if( options.type == 'object' ) {

				workTpl = function( obj, tpl ) {

					if( options.sort )
						var keys = Object.keys( tpl ).sort();
					else
						var keys = tpl;

					for( var key in keys ) {

						if( typeof obj[ key ] == 'undefined' )
							throw ReferenceError( 'Object has no property \'' + key + '\'' );

						if( typeof tpl[ key ].type == 'string' )
							this.write( obj[ key ], tpl[ key ] );
						else if( isObject( tpl[ key ] ) )
							workTpl( obj[ key ], tpl[ key ] );
						else
							throw TypeError( 'Invalid object template' );

					}
				}

				workTpl.call( this, items[ i ], options.template );

			}

	}

	obj.encoder.prototype.compose = function( integer, radix ) {

		this.integers.push( integer );
		this.radii.push( radix );

	}

	obj.encoder.prototype.toString = function( charset ) {

		var binary = false;

		charset = validateCharset( charset );

		if( typeof charset == 'string' )
			var size = charset.length;
		else
			var size = charset[ 1 ] - charset[ 0 ] + 1;

		var radii = 1;
		var current = 0;

		var build = function( integer, radix ) {

			var left = Math.floor( size / radii );

			if( left < 2 ) {

				if( typeof charset == 'string' )
					str += charset.charAt( current );
				else
					str += String.fromCharCode( current + charset[ 0 ] );

				current = 0;
				radii = 1;
				left = size;

			}

			if( left >= radix ) {

				current += radii * integer;
				radii *= radix;

			} else {

				var factor = Math.ceil( radix / left );

				current += radii * Math.floor( integer / factor );
				radii *= left;

				build( integer % factor, factor );

			}

		}

		var str = '';
		for( var i in this.radii )
			build( this.integers[ i ], this.radii[ i ] );

		if( radii != 0 )
			if( typeof charset == 'string' )
				str += charset.charAt( current );
			else
				str += String.fromCharCode( current + charset[ 0 ] );

		return str;

	}

	// our decoder class
	obj.decoder = function( str, charset ) {

		if( !this instanceof obj.decoder )
			return new obj.decoder( str, charset );

		if( typeof str == 'undefined' )
			throw Error( 'Missing first argument' );

		str = str.toString();

		charset = validateCharset( charset );

		if( typeof charset == 'string' )
			this.size = charset.length;
		else
			this.size = charset[ 1 ] - charset[ 0 ] + 1;

		this.str = str;
		this.charset = charset;
		this._next();

	}

	obj.decoder.prototype._next = function() {

		if( typeof this.current == 'undefined' )
			this.pointer = 0;
		 else
			this.pointer ++;

		if( this.pointer == this.str.length )
			throw new Error( 'Unexpected EOD while parsing' );

		this.radii = 1;

		if( typeof this.charset == 'string' ) {

			this.current = this.charset.indexOf( this.str.charAt( this.pointer ) );

			if( this.current == -1 )
				throw Error( 'Byte at ' + this.pointer + ' not found in character set' );

		} else {

			this.current = this.str.charCodeAt( this.pointer ) - this.charset[ 0 ];

			if( this.current > this.charset )
				throw Error( 'Byte at ' + this.pointer + ' does not fit binary range' );

		}

	}

	obj.decoder.prototype.parse = function( radix ) {

		var left = Math.floor( this.size / this.radii );

		if( left == 1 ) {

			if( this.current != 0 )
				throw Error( 'Oversaturated byte at byte ' + this.pointer );

			this._next();
			left = this.size;

		}

		if( left >= radix ) {

			var integer = this.current % radix;
			this.current = Math.floor( this.current / radix );
			this.radii *= radix;

		} else {

			var factor = Math.ceil( radix / left );

			var integer = this.current * factor;
			this.current = Math.floor( this.current / left );
			this.radii *= left;

			integer += this.parse( factor );

		}

		return integer;

	}

	obj.decoder.prototype.read = function( options, count ) {

		var i, obj, chr, size, len, str;

		if( typeof count == 'undefined' )
			var count = 1;
		else if( typeof count != 'number' || count % 1 != 0 || count < 0 )
			throw TypeError( 'Count must be positive integer' );

		options = validateOptions( options );

		if( options.limit )
			count = this.parse( options.limit + 1 );

		if( options.type == 'string' && typeof options.charset == 'string' )
			size = options.charset[ 1 ] - options.charset[ 0 ] + 1;

		var items = new Array();

		for( i = 0; i < count; i++ )
			if( options.type == 'item' ) {

				items.push( options.list[ this.parse( options.list.length ) ] );

			} else if( options.type == 'number' ) {

				items.push( this.parse( ( options.max - options.min ) / options.step + 1 ) * options.step + options.min );

			} else if( options.type == 'boolean' ) {

				items.push( new Boolean( this.parse( 2 ) ) );

			} else if( options.type == 'string' ) {

				len = this.parse( options.max );
				str = '';

				for( chr = 0; chr < len; chr ++ )
					if( typeof options.charset == 'string' )
						str += options.charset.charAt( this.parse( options.charset.length ) );
					else
						str += this.parse( size ) + options.charset[ 0 ];

				items.push( str );

			} else if( options.type == 'object' ) {

				if( typeof options.base == 'function' )
					base = options.base();
				else
					base = options.base;

				if( typeof options.base == 'undefined' || typeof options.base != 'object' )
					base = {};

				workTpl = function( obj, tpl ) {

					if( options.sort )
						var keys = Object.keys( tpl );
					else
						var keys = tpl;

					for( var key in keys ) {

						if( typeof tpl[ key ].type == 'string' )
							obj[ key ] = this.read( tpl[ key ] );
						else if( isObject( tpl[ key ] ) ) {

							if( typeof obj[ key ] == 'undefined' )
								obj[ key ] = {};

							workTpl( obj[ key ], tpl[ key ] );

						} else
							throw TypeError( 'Invalid object template' );

					}
				}

				workTpl.call( this, base, options.template )
				items.push( base );

			}

		if( count == 1 )
			items = items.pop();

		return items;

	}

} ).call( this );<|endoftext|>


<commit_before>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

define('providers/twitter', [
    'providers',
    'jquery','jquery/tmpl',
    'jqueryui/draggable',
    'providers/twitter/adaptor',
    'tmpl!livedesk>providers/twitter',
    'tmpl!livedesk>providers/twitter/user-item',
    'tmpl!livedesk>providers/twitter/web-item',
    'tmpl!livedesk>providers/load-more',
    'tmpl!livedesk>providers/no-results',
    'tmpl!livedesk>providers/loading',
    'jquery'
], function( providers,  $ ) {
$.extend(providers.twitter, {
        initialized: false,
        urlTimeline : 'http://api.twitter.com/1/statuses/following_timeline.json?callback=?&include_entities=true&include_rts=true&screen_name=%(text)s&count=%(count)s',
        urlUser : 'http://api.twitter.com/1/statuses/user_timeline.json?callback=?&include_entities=true&include_rts=true&screen_name=%(text)s&count=%(count)s',
        urlFavorites : 'http://api.twitter.com/1/favorites.json?callback=?&screen_name=%(text)s&count=%(count)s',
	data: [],
	init: function(){
                //console.log('twitter main init');
		if(!this.initialized) {
			this.render();
                        this.adaptor.init();
		}
		this.initialized = true;
	},
	render: function() {
		var self = this;
		this.el.tmpl('livedesk>providers/twitter', {}, function(){
			self.el.on('click', '#twt-search-controls>li', function(ev){
			  $(this).siblings().removeClass('active') .end().addClass('active');
			  var myArr = $(this).attr('id').split('-');
			  //hide all ggl result holders
			  self.el.find('.scroller').css('visibility', 'hidden');
			  //show only the one we need
			  $('#twt-'+myArr[1]+'-holder').css('visibility', 'visible');
			  self.startSearch(true);
			})
			.on('keyup','#twitter-search-text', function(e){
				if(e.keyCode == 13 && $(this).val().length > 0) {
					//enter press on google search text
					//check what search it is
					self.startSearch(true);
				}
			});
		});
	},
        showLoading : function(where) {
             $(where).tmpl('livedesk>providers/loading', function(){
             });
        },
        stopLoading : function(where) {
            $(where).html('');
        },
        startSearch: function(fresh) {
                var self = this;
                fresh = typeof fresh !== 'undefined' ? fresh : false;
                if ( $('#twt-web-tab').hasClass('active') ) {
                    self.doWeb();
                }
                if ( $('#twt-timeline-tab').hasClass('active') ) {
                    self.doTimeline();
                }
                if ( $('#twt-user-tab').hasClass('active') ) {
                    self.doUser();

                }
                if ( $('#twt-favorites-tab').hasClass('active') ) {
                    self.doFavorites();
                }
        },
        doTimeline: function(count) {
            var self = this;
            var text = escape($('#twitter-search-text').val());

            if (text.length < 1) {
                return;
            }
            $('#twt-timeline-more').html('');

            count = typeof count !== 'undefined' ? count : parseInt(8);
            $('#twt-timeline-results').html('');

            this.showLoading('#twt-timeline-more');

            var fullUrl = str.format(this.urlTimeline,{text: text, count: count});
            console.log(fullUrl);
            $.getJSON(fullUrl, {}, function(data){
            self.stopLoading('#twt-timeline-more');
                    var usrData = {
                        results: data
                    }
                    if ( data.length > 0 ) {
                        $.tmpl('livedesk>providers/twitter/user-item', usrData, function(e,o) {
                            $('#twt-timeline-results').append(o).find('.twitter').draggable(
                            {
                                revert: 'invalid',
                                containment:'document',
                                helper: 'clone',
                                appendTo: 'body',
                                zIndex: 2700,
                                clone: true,
                                start: function() {
                                    $(this).data('data', self.adaptor.universal( $(this) ));
                                }
                            }
                            );
                        });

                        var countmore = parseInt(count + 8);
                        var loadMore = {
                            name : 'twitter-timeline-load-more'
                        }
                        $('#twt-timeline-more').tmpl('livedesk>providers/load-more', loadMore, function(){
                            $(this).find('[name="twitter-timeline-load-more"]').on('click', function(){
                                self.doTimeline(countmore);
                            });
                        });
                    } else {
                        $.tmpl('livedesk>providers/no-results', data, function(e,o) {
                            $('#twt-timeline-results').append(o);
                        });
                    }

            });

        },
        doUser : function(count) {
            var self = this;
            var text = escape($('#twitter-search-text').val());

            if (text.length < 1) {
                return;
            }
            $('#twt-user-more').html('');

            count = typeof count !== 'undefined' ? count : parseInt(8);
            $('#twt-user-results').html('');

            this.showLoading('#twt-user-more');
            $.getJSON(str.format(this.urlUser,{text: text, count: count}), {}, function(data){
                    self.stopLoading('#twt-user-more');
                    var usrData = {
                        results: data
                    }

                    if (data.length > 0) {
                        $.tmpl('livedesk>providers/twitter/user-item', usrData, function(e,o) {
                            $('#twt-user-results').append(o).find('.twitter').draggable(
                            {
                                revert: 'invalid',
                                containment:'document',
                                helper: 'clone',
                                appendTo: 'body',
                                zIndex: 2700,
                                clone: true,
                                start: function() {
                                    $(this).data('data', self.adaptor.universal( $(this) ));
                                }
                            }
                            );
                        });

                        var countmore = parseInt(count + 8);
                        var loadMore = {
                            name : 'twitter-user-load-more'
                        }

                        $('#twt-user-more').tmpl('livedesk>providers/load-more', loadMore, function(){
                                $(this).find('[name="twitter-user-load-more"]').on('click', function(){
                                    self.doUser(countmore)
                                });
                        });
                    } else {
                        $.tmpl('livedesk>providers/no-results', data, function(e,o) {
                            $('#twt-user-results').append(o);
                        });
                    }

            });

        },
        doFavorites : function(count) {
            var self = this;
            var text = escape($('#twitter-search-text').val());

            if (text.length < 1) {
                return;
            }
            $('#twt-favorites-more').html('');

            count = typeof count !== 'undefined' ? count : parseInt(8);
            $('#twt-favorites-results').html('');
            this.showLoading('#twt-favorites-more');
            $.getJSON(str.format(this.urlFavorites,{text: text, count: count}), {}, function(data){
                    self.stopLoading('#twt-favorites-more');
                    var usrData = {
                        results: data
                    }

                    if (data.length > 0) {
                        $.tmpl('livedesk>providers/twitter/user-item', usrData, function(e,o) {
                            $('#twt-favorites-results').append(o).find('.twitter').draggable(

                            {
                                revert: 'invalid',
                                containment:'document',
                                helper: 'clone',
                                appendTo: 'body',
                                zIndex: 2700,
                                clone: true,
                                start: function() {
                                    $(this).data('data', self.adaptor.universal( $(this) ));
                                }
                            }

                            );
                        });

                        var countmore = parseInt(count + 8);
                        var loadMore = {
                            name : 'twitter-favorites-load-more'
                        }

                        $('#twt-favorites-more').tmpl('livedesk>providers/load-more', loadMore, function(){
                                $(this).find('[name="twitter-favorites-load-more"]').on('click', function(){
                                    self.doFavorites(countmore)
                                });
                        });
                    } else {
                        $.tmpl('livedesk>providers/no-results', data, function(e,o) {
                            $('#twt-favorites-results').append(o);
                        });
                    }

            });

        },
        doWeb : function(qstring) {
            var self = this;
            var text = escape($('#twitter-search-text').val());
            if (text.length < 1) {
                return;
            }
            $('#twt-web-more').html('');

            qstring = typeof qstring !== 'undefined' ? qstring : '?q='+ text +'&rpp=5&include_entities=true';
            if ( qstring == '?q='+ text +'&rpp=5&include_entities=true' ) {
                $('#twt-web-results').html('');
            }

            var mainUrl = 'http://search.twitter.com/search.json';
            var url = mainUrl + qstring + '&result_type=mixed&callback=?';
            this.showLoading('#twt-web-more');
            $.getJSON(url, {}, function(data){
                    self.stopLoading('#twt-web-more');
                    if (data.results.length > 0) {
                        $.tmpl('livedesk>providers/twitter/web-item', data, function(e,o) {
                                $('#twt-web-results').append(o).find('.twitter').draggable(

                                {
                                    revert: 'invalid',
                                    containment:'document',
                                    helper: 'clone',
                                    appendTo: 'body',
                                    zIndex: 2700,
                                    clone: true,
                                    start: function() {
                                        $(this).data('data', self.adaptor.universal( $(this) ));
                                    }
                                }

                                );
                        });

                        var loadMore = {
                            name : 'twitter-web-load-more'
                        }

                        if (data.next_page) {
                            $('#twt-web-more').tmpl('livedesk>providers/load-more', loadMore, function(){
                                    $(this).find('[name="twitter-web-load-more"]').on('click', function(){
                                        self.doWeb(data.next_page)
                                    });
                            });
                        }
                    } else {
                        $.tmpl('livedesk>providers/no-results', data, function(e,o) {
                            $('#twt-web-results').append(o);
                        });
                    }

            });

        }
});
return providers;
});<commit_msg>NR-151 : Necessary core features features and fixes<commit_after>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

define('providers/twitter', [
    'providers',
    'jquery','jquery/tmpl',
    'jqueryui/draggable',
    'providers/twitter/adaptor',
    'tmpl!livedesk>providers/twitter',
    'tmpl!livedesk>providers/twitter/user-item',
    'tmpl!livedesk>providers/twitter/web-item',
    'tmpl!livedesk>providers/load-more',
    'tmpl!livedesk>providers/no-results',
    'tmpl!livedesk>providers/loading',
    'jquery'
], function( providers,  $ ) {
$.extend(providers.twitter, {
        initialized: false,
        urlTimeline : 'http://api.twitter.com/1/statuses/following_timeline.json?callback=?&include_entities=true&include_rts=true&screen_name=%(text)s&count=%(count)s',
        urlUser : 'http://api.twitter.com/1/statuses/user_timeline.json?callback=?&include_entities=true&include_rts=true&screen_name=%(text)s&count=%(count)s',
        urlFavorites : 'http://api.twitter.com/1/favorites.json?callback=?&screen_name=%(text)s&count=%(count)s',
	data: [],
	init: function(){
                //console.log('twitter main init');
		if(!this.initialized) {
			this.render();
                        this.adaptor.init();
		}
		this.initialized = true;
	},
	render: function() {
		var self = this;
		this.el.tmpl('livedesk>providers/twitter', {}, function(){
			self.el.on('click', '#twt-search-controls>li', function(ev){
			  $(this).siblings().removeClass('active') .end().addClass('active');
			  var myArr = $(this).attr('id').split('-');
			  //hide all ggl result holders
			  self.el.find('.scroller').css('visibility', 'hidden');
			  //show only the one we need
			  $('#twt-'+myArr[1]+'-holder').css('visibility', 'visible');
			  self.startSearch(true);
			})
			.on('keyup','#twitter-search-text', function(e){
				if(e.keyCode == 13 && $(this).val().length > 0) {
					//enter press on google search text
					//check what search it is
					self.startSearch(true);
				}
			});
		});
	},
        showLoading : function(where) {
             $(where).tmpl('livedesk>providers/loading', function(){
             });
        },
        stopLoading : function(where) {
            $(where).html('');
        },
        startSearch: function(fresh) {
                var self = this;
                fresh = typeof fresh !== 'undefined' ? fresh : false;
                if ( $('#twt-web-tab').hasClass('active') ) {
                    self.doWeb();
                }
                if ( $('#twt-timeline-tab').hasClass('active') ) {
                    self.doTimeline();
                }
                if ( $('#twt-user-tab').hasClass('active') ) {
                    self.doUser();

                }
                if ( $('#twt-favorites-tab').hasClass('active') ) {
                    self.doFavorites();
                }
        },
        doTimeline: function(count) {
            var self = this;
            var text = escape($('#twitter-search-text').val());

            if (text.length < 1) {
                return;
            }
            $('#twt-timeline-more').html('');

            count = typeof count !== 'undefined' ? count : parseInt(8);
            $('#twt-timeline-results').html('');

            this.showLoading('#twt-timeline-more');

            var fullUrl = str.format(this.urlTimeline,{text: text, count: count});
            console.log(fullUrl);
            $.getJSON(fullUrl, {}, function(data){
            self.stopLoading('#twt-timeline-more');
                    var usrData = {
                        results: data
                    }
                    if ( data.length > 0 ) {
                        $.tmpl('livedesk>providers/twitter/user-item', usrData, function(e,o) {
                            $('#twt-timeline-results').append(o).find('.twitter').draggable(
                            {
                                revert: 'invalid',
                                helper: 'clone',
                                appendTo: 'body',
                                zIndex: 2700,
                                clone: true,
                                start: function() {
                                    $(this).data('data', self.adaptor.universal( $(this) ));
                                }
                            }
                            );
                        });

                        var countmore = parseInt(count + 8);
                        var loadMore = {
                            name : 'twitter-timeline-load-more'
                        }
                        $('#twt-timeline-more').tmpl('livedesk>providers/load-more', loadMore, function(){
                            $(this).find('[name="twitter-timeline-load-more"]').on('click', function(){
                                self.doTimeline(countmore);
                            });
                        });
                    } else {
                        $.tmpl('livedesk>providers/no-results', data, function(e,o) {
                            $('#twt-timeline-results').append(o);
                        });
                    }

            });

        },
        doUser : function(count) {
            var self = this;
            var text = escape($('#twitter-search-text').val());

            if (text.length < 1) {
                return;
            }
            $('#twt-user-more').html('');

            count = typeof count !== 'undefined' ? count : parseInt(8);
            $('#twt-user-results').html('');

            this.showLoading('#twt-user-more');
            $.getJSON(str.format(this.urlUser,{text: text, count: count}), {}, function(data){
                    self.stopLoading('#twt-user-more');
                    var usrData = {
                        results: data
                    }

                    if (data.length > 0) {
                        $.tmpl('livedesk>providers/twitter/user-item', usrData, function(e,o) {
                            $('#twt-user-results').append(o).find('.twitter').draggable(
                            {
                                revert: 'invalid',
                                helper: 'clone',
                                appendTo: 'body',
                                zIndex: 2700,
                                clone: true,
                                start: function() {
                                    $(this).data('data', self.adaptor.universal( $(this) ));
                                }
                            }
                            );
                        });

                        var countmore = parseInt(count + 8);
                        var loadMore = {
                            name : 'twitter-user-load-more'
                        }

                        $('#twt-user-more').tmpl('livedesk>providers/load-more', loadMore, function(){
                                $(this).find('[name="twitter-user-load-more"]').on('click', function(){
                                    self.doUser(countmore)
                                });
                        });
                    } else {
                        $.tmpl('livedesk>providers/no-results', data, function(e,o) {
                            $('#twt-user-results').append(o);
                        });
                    }

            });

        },
        doFavorites : function(count) {
            var self = this;
            var text = escape($('#twitter-search-text').val());

            if (text.length < 1) {
                return;
            }
            $('#twt-favorites-more').html('');

            count = typeof count !== 'undefined' ? count : parseInt(8);
            $('#twt-favorites-results').html('');
            this.showLoading('#twt-favorites-more');
            $.getJSON(str.format(this.urlFavorites,{text: text, count: count}), {}, function(data){
                    self.stopLoading('#twt-favorites-more');
                    var usrData = {
                        results: data
                    }

                    if (data.length > 0) {
                        $.tmpl('livedesk>providers/twitter/user-item', usrData, function(e,o) {
                            $('#twt-favorites-results').append(o).find('.twitter').draggable(

                            {
                                revert: 'invalid',
                                helper: 'clone',
                                appendTo: 'body',
                                zIndex: 2700,
                                clone: true,
                                start: function() {
                                    $(this).data('data', self.adaptor.universal( $(this) ));
                                }
                            }

                            );
                        });

                        var countmore = parseInt(count + 8);
                        var loadMore = {
                            name : 'twitter-favorites-load-more'
                        }

                        $('#twt-favorites-more').tmpl('livedesk>providers/load-more', loadMore, function(){
                                $(this).find('[name="twitter-favorites-load-more"]').on('click', function(){
                                    self.doFavorites(countmore)
                                });
                        });
                    } else {
                        $.tmpl('livedesk>providers/no-results', data, function(e,o) {
                            $('#twt-favorites-results').append(o);
                        });
                    }

            });

        },
        doWeb : function(qstring) {
            var self = this;
            var text = escape($('#twitter-search-text').val());
            if (text.length < 1) {
                return;
            }
            $('#twt-web-more').html('');

            qstring = typeof qstring !== 'undefined' ? qstring : '?q='+ text +'&rpp=5&include_entities=true';
            if ( qstring == '?q='+ text +'&rpp=5&include_entities=true' ) {
                $('#twt-web-results').html('');
            }

            var mainUrl = 'http://search.twitter.com/search.json';
            var url = mainUrl + qstring + '&result_type=mixed&callback=?';
            this.showLoading('#twt-web-more');
            $.getJSON(url, {}, function(data){
                    self.stopLoading('#twt-web-more');
                    if (data.results.length > 0) {
                        $.tmpl('livedesk>providers/twitter/web-item', data, function(e,o) {
                                $('#twt-web-results').append(o).find('.twitter').draggable(

                                {
                                    revert: 'invalid',
                                    helper: 'clone',
                                    appendTo: 'body',
                                    zIndex: 2700,
                                    clone: true,
                                    start: function() {
                                        $(this).data('data', self.adaptor.universal( $(this) ));
                                    }
                                }

                                );
                        });

                        var loadMore = {
                            name : 'twitter-web-load-more'
                        }

                        if (data.next_page) {
                            $('#twt-web-more').tmpl('livedesk>providers/load-more', loadMore, function(){
                                    $(this).find('[name="twitter-web-load-more"]').on('click', function(){
                                        self.doWeb(data.next_page)
                                    });
                            });
                        }
                    } else {
                        $.tmpl('livedesk>providers/no-results', data, function(e,o) {
                            $('#twt-web-results').append(o);
                        });
                    }

            });

        }
});
return providers;
});<|endoftext|>


<commit_before>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

define('providers/twitter', [
    'providers',
    'jquery','jquery/tmpl',
    'jquery/jsonp',
    'jqueryui/draggable',
    'providers/twitter/adaptor',
    'tmpl!livedesk>providers/twitter',
    'tmpl!livedesk>providers/twitter/user-item',
    'tmpl!livedesk>providers/twitter/web-item',
    'tmpl!livedesk>providers/load-more',
    'tmpl!livedesk>providers/no-results',
    'tmpl!livedesk>providers/jsonp-error',
    'tmpl!livedesk>providers/loading',
], function( providers,  $ ) {
$.extend(providers.twitter, {
        initialized: false,
        urlTimeline : 'http://api.twitter.com/1/statuses/following_timeline.json?callback=?&include_entities=true&include_rts=true&screen_name=%(text)s&page=%(page)s',

        urlUser : 'http://api.twitter.com/1/statuses/user_timeline.json?callback=?&include_entities=true&include_rts=true&screen_name=%(text)s&page=%(page)s',

        urlFavorites : 'http://api.twitter.com/1/favorites.json?callback=?&screen_name=%(text)s&page=%(page)s',

	data: [],
	init: function(){
                //console.log('twitter main init');
		if(!this.initialized) {
			this.render();
                        this.adaptor.init();
		}
		this.initialized = true;
	},
	render: function() {
		var self = this;
		this.el.tmpl('livedesk>providers/twitter', {}, function(){
			self.el.on('click', '#twt-search-controls>li', function(ev){
			  $(this).siblings().removeClass('active') .end().addClass('active');
			  var myArr = $(this).attr('id').split('-');
			  //hide all ggl result holders
			  self.el.find('.scroller').css('visibility', 'hidden');
			  //show only the one we need
			  $('#twt-'+myArr[1]+'-holder').css('visibility', 'visible');
			  self.startSearch(true);
			})
			.on('keyup','#twitter-search-text', function(e){
				if(e.keyCode == 13 && $(this).val().length > 0) {
					//enter press on google search text
					//check what search it is
					self.startSearch(true);
				}
			});
		});
	},
        showLoading : function(where) {
             $(where).tmpl('livedesk>providers/loading', function(){
             });
        },
        stopLoading : function(where) {
            $(where).html('');
        },
        noResults : function(where) {
            $.tmpl('livedesk>providers/no-results', {}, function(e,o) {
                $(where).append(o);
            });
        },
        jsonpError : function(where) {
            $.tmpl('livedesk>providers/jsonp-error', {}, function(e,o) {
                $(where).html(o);
            });
        },
        startSearch: function(fresh) {
                var self = this;
                fresh = typeof fresh !== 'undefined' ? fresh : false;
                if ( $('#twt-web-tab').hasClass('active') ) {
                    self.doWeb();
                }
                if ( $('#twt-timeline-tab').hasClass('active') ) {
                    self.doTimeline();
                }
                if ( $('#twt-user-tab').hasClass('active') ) {
                    self.doUser();

                }
                if ( $('#twt-favorites-tab').hasClass('active') ) {
                    self.doFavorites(1);
                }
        },
        doTimeline: function(page) {
                var self = this;
                var text = escape($('#twitter-search-text').val());
                if (text.length < 1) {
                    return;
                }
                $('#twt-timeline-more').html('');
                page = typeof page !== 'undefined' ? page : 1;
                if (page == 1) {
                    $('#twt-timeline-results').html('');
                    self.data = [];
                }
                this.showLoading('#twt-timeline-more');
                var fullUrl = str.format(this.urlTimeline,{text: text, page: page});
                $.jsonp({
                    url : fullUrl,
                    success : function(data){
                        self.stopLoading('#twt-timeline-more');
                        if ( data.length > 0 || page > 1) {
                            $.tmpl('livedesk>providers/twitter/user-item', {results: data}, function(e,o) {
                                $('#twt-timeline-results').append(o).find('.twitter').draggable({revert: 'invalid',helper: 'clone',appendTo: 'body',zIndex: 2700,clone: true,
                                    start: function() {
                                        $(this).data('data', self.adaptor.universal( $(this) ));
                                    }
                                });
                            });
                            if (data.length > 19) {
                                $('#twt-timeline-more').tmpl('livedesk>providers/load-more', {name : 'twitter-timeline-load-more'}, function(){
                                    $(this).find('[name="twitter-timeline-load-more"]').on('click', function(){
                                        self.doTimeline(parseInt(page + 1));
                                    });
                                });
                            }

                        } else {
                            self.noResults('#twt-timeline-results');
                        }
                    },
                    error : function(){
                        self.jsonpError('#twt-timeline-more');
                    }
                })
            },
        doUser : function(page) {
            var self = this;
            var text = escape($('#twitter-search-text').val());
            if (text.length < 1) {
                return;
            }

            page = typeof page !== 'undefined' ? page : 1;
            if (page == 1) {
                $('#twt-user-results').html('');
            }
            this.showLoading('#twt-user-more');
            var fullUrl = str.format(this.urlUser,{text: text, page: page});
            $.jsonp({
                url : fullUrl,
                success : function(data){
                    self.stopLoading('#twt-user-more');
                    if (data.length > 0 || page > 1) {
                        $.tmpl('livedesk>providers/twitter/user-item', {results: data}, function(e,o) {
                            $('#twt-user-results').append(o).find('.twitter').draggable({revert: 'invalid',helper: 'clone',appendTo: 'body',zIndex: 2700,clone: true,
                                start: function() {
                                    $(this).data('data', self.adaptor.universal( $(this) ));
                                }
                            });
                        });

                        if (data.length > 19) {
                            $('#twt-user-more').tmpl('livedesk>providers/load-more', {name : 'twitter-user-load-more'}, function(){
                                $(this).find('[name="twitter-user-load-more"]').on('click', function(){
                                    self.doUser(parseInt(page + 1))
                                });
                            });
                        }
                    } else {
                        self.noResults('#twt-user-results');
                    }
                },
                error : function() {
                    self.jsonpError('#twt-user-more');
                }
            });

        },
        doFavorites : function(page) {
            var self = this;
            var text = escape($('#twitter-search-text').val());
            if (text.length < 1) {
                return;
            }
            page = typeof page !== 'undefined' ? page : 1;
            if( page == 1 ) {
                $('#twt-favorites-results').html('');
            }
            this.showLoading('#twt-favorites-more');
            var fullUrl = str.format(this.urlFavorites,{text: text, page: page});
            $.jsonp({
                url: fullUrl,
                success : function(data) {
                    self.stopLoading('#twt-favorites-more');
                    if (data.length > 0 || page > 1) {
                        //feed results to template
                        $.tmpl('livedesk>providers/twitter/user-item', {results: data}, function(e,o) {
                            $('#twt-favorites-results').append(o).find('.twitter').draggable({revert: 'invalid',helper: 'clone',appendTo: 'body',zIndex: 2700,clone: true,
                                start: function() {
                                    $(this).data('data', self.adaptor.universal( $(this) ));
                                }
                            });
                        });
                        //handle load more button
                        if (data.length > 19) {
                            $('#twt-favorites-more').tmpl('livedesk>providers/load-more', {name : 'twitter-favorites-load-more'}, function(){
                                    $(this).find('[name="twitter-favorites-load-more"]').on('click', function(){
                                        self.doFavorites(parseInt(page + 1));
                                    });
                            });
                        }
                    } else {
                        self.noResults('#twt-favorites-results');
                    }
                },
                error : function(xOptions, message) {
                    self.jsonpError('#twt-favorites-more');
                }
            });
        },
        doWeb : function(qstring) {
            var self = this;
            var text = escape($('#twitter-search-text').val());
            if (text.length < 1) {
                return;
            }
            $('#twt-web-more').html('');

            qstring = typeof qstring !== 'undefined' ? qstring : '?q='+ text +'&include_entities=true';
            if ( qstring == '?q='+ text +'&include_entities=true' ) {
                $('#twt-web-results').html('');
            }

            var mainUrl = 'http://search.twitter.com/search.json';
            var url = mainUrl + qstring + '&result_type=mixed&callback=?';
            this.showLoading('#twt-web-more');

            $.jsonp({
               url : url,
               success : function(data){
                    self.stopLoading('#twt-web-more');
                    if (data.results.length > 0) {
                        $.tmpl('livedesk>providers/twitter/web-item', data, function(e,o) {
                                $('#twt-web-results').append(o).find('.twitter').draggable(
                                {
                                    revert: 'invalid',
                                    helper: 'clone',
                                    appendTo: 'body',
                                    zIndex: 2700,
                                    clone: true,
                                    start: function() {
                                        $(this).data('data', self.adaptor.universal( $(this) ));
                                    }
                                });
                        });
                        if (data.next_page) {
                            $('#twt-web-more').tmpl('livedesk>providers/load-more', {name : 'twitter-web-load-more'}, function(){
                                    $(this).find('[name="twitter-web-load-more"]').on('click', function(){
                                        self.doWeb(data.next_page)
                                    });
                            });
                        }
                    } else {
                        self.noResults('#twt-web-results');
                    }
            },
            error : function() {
                self.jsonpError('#twt-web-more');
            }
            });
        }
});
return providers;
});<commit_msg>NR-170T : witter search - should pull results from the "All tweets" feed as default<commit_after>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

define('providers/twitter', [
    'providers',
    'jquery','jquery/tmpl',
    'jquery/jsonp',
    'jqueryui/draggable',
    'providers/twitter/adaptor',
    'tmpl!livedesk>providers/twitter',
    'tmpl!livedesk>providers/twitter/user-item',
    'tmpl!livedesk>providers/twitter/web-item',
    'tmpl!livedesk>providers/load-more',
    'tmpl!livedesk>providers/no-results',
    'tmpl!livedesk>providers/jsonp-error',
    'tmpl!livedesk>providers/loading',
], function( providers,  $ ) {
$.extend(providers.twitter, {
        initialized: false,
        urlTimeline : 'http://api.twitter.com/1/statuses/following_timeline.json?callback=?&include_entities=true&include_rts=true&screen_name=%(text)s&page=%(page)s',

        urlUser : 'http://api.twitter.com/1/statuses/user_timeline.json?callback=?&include_entities=true&include_rts=true&screen_name=%(text)s&page=%(page)s',

        urlFavorites : 'http://api.twitter.com/1/favorites.json?callback=?&screen_name=%(text)s&page=%(page)s',

	data: [],
	init: function(){
                //console.log('twitter main init');
		if(!this.initialized) {
			this.render();
                        this.adaptor.init();
		}
		this.initialized = true;
	},
	render: function() {
		var self = this;
		this.el.tmpl('livedesk>providers/twitter', {}, function(){
			self.el.on('click', '#twt-search-controls>li', function(ev){
			  $(this).siblings().removeClass('active') .end().addClass('active');
			  var myArr = $(this).attr('id').split('-');
			  //hide all ggl result holders
			  self.el.find('.scroller').css('visibility', 'hidden');
			  //show only the one we need
			  $('#twt-'+myArr[1]+'-holder').css('visibility', 'visible');
			  self.startSearch(true);
			})
			.on('keyup','#twitter-search-text', function(e){
				if(e.keyCode == 13 && $(this).val().length > 0) {
					//enter press on google search text
					//check what search it is
					self.startSearch(true);
				}
			});
		});
	},
        showLoading : function(where) {
             $(where).tmpl('livedesk>providers/loading', function(){
             });
        },
        stopLoading : function(where) {
            $(where).html('');
        },
        noResults : function(where) {
            $.tmpl('livedesk>providers/no-results', {}, function(e,o) {
                $(where).append(o);
            });
        },
        jsonpError : function(where) {
            $.tmpl('livedesk>providers/jsonp-error', {}, function(e,o) {
                $(where).html(o);
            });
        },
        startSearch: function(fresh) {
                var self = this;
                fresh = typeof fresh !== 'undefined' ? fresh : false;
                if ( $('#twt-web-tab').hasClass('active') ) {
                    self.doWeb();
                }
                if ( $('#twt-timeline-tab').hasClass('active') ) {
                    self.doTimeline();
                }
                if ( $('#twt-user-tab').hasClass('active') ) {
                    self.doUser();

                }
                if ( $('#twt-favorites-tab').hasClass('active') ) {
                    self.doFavorites(1);
                }
        },
        doTimeline: function(page) {
                var self = this;
                var text = escape($('#twitter-search-text').val());
                if (text.length < 1) {
                    return;
                }
                $('#twt-timeline-more').html('');
                page = typeof page !== 'undefined' ? page : 1;
                if (page == 1) {
                    $('#twt-timeline-results').html('');
                    self.data = [];
                }
                this.showLoading('#twt-timeline-more');
                var fullUrl = str.format(this.urlTimeline,{text: text, page: page});
                $.jsonp({
                    url : fullUrl,
                    success : function(data){
                        self.stopLoading('#twt-timeline-more');
                        if ( data.length > 0 || page > 1) {
                            $.tmpl('livedesk>providers/twitter/user-item', {results: data}, function(e,o) {
                                $('#twt-timeline-results').append(o).find('.twitter').draggable({revert: 'invalid',helper: 'clone',appendTo: 'body',zIndex: 2700,clone: true,
                                    start: function() {
                                        $(this).data('data', self.adaptor.universal( $(this) ));
                                    }
                                });
                            });
                            if (data.length > 19) {
                                $('#twt-timeline-more').tmpl('livedesk>providers/load-more', {name : 'twitter-timeline-load-more'}, function(){
                                    $(this).find('[name="twitter-timeline-load-more"]').on('click', function(){
                                        self.doTimeline(parseInt(page + 1));
                                    });
                                });
                            }

                        } else {
                            self.noResults('#twt-timeline-results');
                        }
                    },
                    error : function(){
                        self.jsonpError('#twt-timeline-more');
                    }
                })
            },
        doUser : function(page) {
            var self = this;
            var text = escape($('#twitter-search-text').val());
            if (text.length < 1) {
                return;
            }

            page = typeof page !== 'undefined' ? page : 1;
            if (page == 1) {
                $('#twt-user-results').html('');
            }
            this.showLoading('#twt-user-more');
            var fullUrl = str.format(this.urlUser,{text: text, page: page});
            $.jsonp({
                url : fullUrl,
                success : function(data){
                    self.stopLoading('#twt-user-more');
                    if (data.length > 0 || page > 1) {
                        $.tmpl('livedesk>providers/twitter/user-item', {results: data}, function(e,o) {
                            $('#twt-user-results').append(o).find('.twitter').draggable({revert: 'invalid',helper: 'clone',appendTo: 'body',zIndex: 2700,clone: true,
                                start: function() {
                                    $(this).data('data', self.adaptor.universal( $(this) ));
                                }
                            });
                        });

                        if (data.length > 19) {
                            $('#twt-user-more').tmpl('livedesk>providers/load-more', {name : 'twitter-user-load-more'}, function(){
                                $(this).find('[name="twitter-user-load-more"]').on('click', function(){
                                    self.doUser(parseInt(page + 1))
                                });
                            });
                        }
                    } else {
                        self.noResults('#twt-user-results');
                    }
                },
                error : function() {
                    self.jsonpError('#twt-user-more');
                }
            });

        },
        doFavorites : function(page) {
            var self = this;
            var text = escape($('#twitter-search-text').val());
            if (text.length < 1) {
                return;
            }
            page = typeof page !== 'undefined' ? page : 1;
            if( page == 1 ) {
                $('#twt-favorites-results').html('');
            }
            this.showLoading('#twt-favorites-more');
            var fullUrl = str.format(this.urlFavorites,{text: text, page: page});
            $.jsonp({
                url: fullUrl,
                success : function(data) {
                    self.stopLoading('#twt-favorites-more');
                    if (data.length > 0 || page > 1) {
                        //feed results to template
                        $.tmpl('livedesk>providers/twitter/user-item', {results: data}, function(e,o) {
                            $('#twt-favorites-results').append(o).find('.twitter').draggable({revert: 'invalid',helper: 'clone',appendTo: 'body',zIndex: 2700,clone: true,
                                start: function() {
                                    $(this).data('data', self.adaptor.universal( $(this) ));
                                }
                            });
                        });
                        //handle load more button
                        if (data.length > 19) {
                            $('#twt-favorites-more').tmpl('livedesk>providers/load-more', {name : 'twitter-favorites-load-more'}, function(){
                                    $(this).find('[name="twitter-favorites-load-more"]').on('click', function(){
                                        self.doFavorites(parseInt(page + 1));
                                    });
                            });
                        }
                    } else {
                        self.noResults('#twt-favorites-results');
                    }
                },
                error : function(xOptions, message) {
                    self.jsonpError('#twt-favorites-more');
                }
            });
        },
        doWeb : function(qstring) {
            var self = this;
            var text = escape($('#twitter-search-text').val());
            if (text.length < 1) {
                return;
            }
            $('#twt-web-more').html('');

            qstring = typeof qstring !== 'undefined' ? qstring : '?q='+ text +'&include_entities=true';
            if ( qstring == '?q='+ text +'&include_entities=true' ) {
                $('#twt-web-results').html('');
            }

            var mainUrl = 'http://search.twitter.com/search.json';
            var url = mainUrl + qstring + '&result_type=recent&callback=?';
            this.showLoading('#twt-web-more');

            $.jsonp({
               url : url,
               success : function(data){
                    self.stopLoading('#twt-web-more');
                    if (data.results.length > 0) {
                        $.tmpl('livedesk>providers/twitter/web-item', data, function(e,o) {
                                $('#twt-web-results').append(o).find('.twitter').draggable(
                                {
                                    revert: 'invalid',
                                    helper: 'clone',
                                    appendTo: 'body',
                                    zIndex: 2700,
                                    clone: true,
                                    start: function() {
                                        $(this).data('data', self.adaptor.universal( $(this) ));
                                    }
                                });
                        });
                        if (data.next_page) {
                            $('#twt-web-more').tmpl('livedesk>providers/load-more', {name : 'twitter-web-load-more'}, function(){
                                    $(this).find('[name="twitter-web-load-more"]').on('click', function(){
                                        self.doWeb(data.next_page)
                                    });
                            });
                        }
                    } else {
                        self.noResults('#twt-web-results');
                    }
            },
            error : function() {
                self.jsonpError('#twt-web-more');
            }
            });
        }
});
return providers;
});<|endoftext|>


<commit_before>(function(window){
  if ("Promise" in window) {
    return ;
  }
  function Promise(executor) {
    if (typeof executor !== "function") {
      throw Error("Promise resolver " + executor + " is not a function");
    }

    var queue = [];

    var state = "pending";
    var statevalue = null;

    this.length = 1;

    this.all = function(iterable) {
    };

    this.race = function(iterable) {

    };

    this.reject = function(reason) {
      state = "rejected";
      statevalue = reason;
      processQueue();
    };

    this.resolve = function(value) {
      state = "fulfilled";
      statevalue = value;
      processQueue();
    };

    function processQueue() {
      if (state === "fulfilled") {
        var succCallback = queue.shift()["success"];
        succCallback && succCallback(statevalue);
      } else if (state === "rejected") {
        var errCallback = queue.shift()["error"];
        errCallback && errCallback(statevalue);
      }
    }

    this.getState = function() {
      return state;
    };

    this.getStateValue = function() {
      return statevalue;
    };

    this.getQueue = function() {
      return queue;
    }

    executor.call(this, this.resolve, this.reject);
  }
  Promise.prototype.catch = function(onRejected) {

    return this;
  };
  Promise.prototype.then = function(onFulfilled, onRejected) {
    this.getQueue().push({
      success: onFulfilled,
      error: onRejected
    });
    return this;
  };

  window.Promise = Promise;
}(window));<commit_msg>Use strict mode<commit_after>(function(window){
  "use strict";
  if ("Promise" in window) {
    return ;
  }
  function Promise(executor) {
    if (typeof executor !== "function") {
      throw Error("Promise resolver " + executor + " is not a function");
    }

    var queue = [];

    var state = "pending";
    var statevalue = null;

    this.length = 1;

    this.all = function(iterable) {
    };

    this.race = function(iterable) {

    };

    this.reject = function(reason) {
      state = "rejected";
      statevalue = reason;
      processQueue();
    };

    this.resolve = function(value) {
      state = "fulfilled";
      statevalue = value;
      processQueue();
    };

    function processQueue() {
      if (state === "fulfilled") {
        var succCallback = queue.shift()["success"];
        succCallback && succCallback(statevalue);
      } else if (state === "rejected") {
        var errCallback = queue.shift()["error"];
        errCallback && errCallback(statevalue);
      }
    }

    this.getState = function() {
      return state;
    };

    this.getStateValue = function() {
      return statevalue;
    };

    this.getQueue = function() {
      return queue;
    }

    executor.call(this, this.resolve, this.reject);
  }
  Promise.prototype.catch = function(onRejected) {

    return this;
  };
  Promise.prototype.then = function(onFulfilled, onRejected) {
    this.getQueue().push({
      success: onFulfilled,
      error: onRejected
    });
    return this;
  };

  window.Promise = Promise;
}(window));
<|endoftext|>


<commit_before>'use strict';

const WebMergeAPI = require('.');

const promiseFromCallback = fn => new Promise((resolve, reject) => {
  fn((err, response) => {
    if (err) return reject(err);
    return resolve(response);
  });
});

const promisify = (fn, ...args) => promiseFromCallback(cb => fn(...args, cb));

class WebMergePromiseAPI extends WebMergeAPI {
  mergeDocument(...args) {
    return promisify(super.mergeDocument, ...args);
  }

  createDocument(...args) {
    return promisify(super.createDocument, ...args);
  }

  updateDocument(...args) {
    return promisify(super.updateDocument, ...args);
  }

  getDocuments(...args) {
    return promisify(super.getDocuments, ...args);
  }

  getDocument(...args) {
    return promisify(super.getDocument, ...args);
  }

  getDocumentFields(...args) {
    return promisify(super.getDocumentFields, ...args);
  }
}

module.exports = WebMergePromiseAPI;
<commit_msg>Use callback.<commit_after>'use strict';

const WebMergeAPI = require('.');

const promiseFromCallback = fn => new Promise((resolve, reject) => {
  fn((err, response) => {
    if (err) return reject(err);
    return resolve(response);
  });
});

const promisify = (fn, ...args) => promiseFromCallback(cb => fn(...args, cb));

class WebMergePromiseAPI extends WebMergeAPI {
  mergeDocument(...args) {
    return promiseFromCallback(cb => super.mergeDocument(...args, cb));
  }

  createDocument(...args) {
    return promiseFromCallback(cb => super.createDocument(...args, cb));
  }

  updateDocument(...args) {
    return promiseFromCallback(cb => super.updateDocument(...args, cb));
  }

  getDocuments(...args) {
    return promiseFromCallback(cb => super.getDocuments(...args, cb));
  }

  getDocument(...args) {
    return promiseFromCallback(cb => super.getDocument(...args, cb));
  }

  getDocumentFields(...args) {
    return promiseFromCallback(cb => super.getDocumentFields(...args, cb));
  }
}

module.exports = WebMergePromiseAPI;
<|endoftext|>


<commit_before>'use strict';

var imagesArray = [];

function Image(productName, filePath) {
  this.productName = productName;
  this.filePath = filePath;
  this.numClicks = 0;
  this.timesDisplayed = 0;
  imagesArray.push(this);
}
var bagImage = new Image('bag','bag.jpg');
var bananaImage = new Image('banana', 'banana.jpg');
var bootsImage = new Image('boots', 'boots.jpg');
var chairImage = new Image('chair', 'chair.jpg');
var cthulhuImage = new Image('cthulhu', 'cthulhu.jpg');
var dragonImage = new Image('dragon', 'dragon.jpg');
var penImage = new Image('pen', 'pen.jpg');
var scissorsImage = new Image('scissors', 'scissors.jpg');
var sharkImage = new Image('shark', 'shark.jpg');
var sweepImage = new Image('sweep', 'sweep.png');
var unicornImage = new Image('unicorn', 'unicorn.jpg');
var usbImage = new Image('usb', 'usb.gif');
var water_canImage = new Image('water_can', 'water-can.jpg');// BEWARE: underscore vs. dash
var wine_glassImage = new Image('wine_glass', 'wine-glass.jpg');

var image1 = document.getElementById('image1');
var image2 = document.getElementById('image2');
var image3 = document.getElementById('image3');
var randomNumber1 = 0;
var randomNumber2 = 0;
var randomNumber3 = 0;
var globalClickTracker = 0;

var arrayOfArrays = [[],[],[]];

function getThreeImages() {
  getRandomImage1();
  getRandomImage2();
  getRandomImage3();
  duplicatePreventer();
}
function duplicatePreventer() {
  while (image1.src === image2.src || image1.src === image3.src || image2.src === image3.src){
    getThreeImages();
  }
}
function getRandomImage1() {
  randomNumber1 = Math.floor(Math.random() * imagesArray.length);
  document.getElementById('image1').src= 'images-to-be-used/' +  imagesArray[randomNumber1].filePath;
}
function getRandomImage2() {
  randomNumber2 = Math.floor(Math.random() * imagesArray.length);
  document.getElementById('image2').src= 'images-to-be-used/' +  imagesArray[randomNumber2].filePath;
}
function getRandomImage3() {
  randomNumber3 = Math.floor(Math.random() * imagesArray.length);
  document.getElementById('image3').src= 'images-to-be-used/' +  imagesArray[randomNumber3].filePath;
}

var button = document.getElementById('loadButton');

var image1Clicks = 0;
var image2Clicks = 0;
var image3Clicks = 0;

function handleClickOnFirst() {
  imagesArray[randomNumber1].timesDisplayed += 1;
  globalClickTracker += 1;
  if (globalClickTracker === 15) {
    button.removeAttribute('hidden');
  }
  imagesArray[randomNumber1].numClicks += 1;
  getThreeImages();
}
function handleClickOnSecond() {
  imagesArray[randomNumber2].timesDisplayed += 1;
  globalClickTracker += 1;
  if (globalClickTracker === 15) {
    button.removeAttribute('hidden');
  }
  imagesArray[randomNumber2].numClicks += 1;
  getThreeImages();
}
function handleClickOnThird() {
  imagesArray[randomNumber3].timesDisplayed += 1;
  globalClickTracker += 1;
  if (globalClickTracker === 15) {
    button.removeAttribute('hidden');
  }
  imagesArray[randomNumber3].numClicks += 1;
  getThreeImages();
}

image1.addEventListener('click', handleClickOnFirst);
image2.addEventListener('click', handleClickOnSecond);
image3.addEventListener('click', handleClickOnThird);
button.addEventListener('click', handleButton);
getThreeImages();

function handleButton() {
  for (var i = 0; i < imagesArray.length; i++) {
  }
  makeChart();
}
function makeChart() {
  for (var i = 0; i < imagesArray.length; i++) {
    arrayOfArrays[0][i] = imagesArray[i].productName;
    arrayOfArrays[1][i] = imagesArray[i].numClicks;
    arrayOfArrays[2][i] = imagesArray[i].timesDisplayed;
  }
  var data = {
    labels: ['bag', 'banana', 'chair', 'cthulhu', 'dragon', 'pen', 'scissors', 'shark', 'sweep', 'unicorn', 'usb', 'water_can', 'wine_glass'],
    datasets: [
      {
        fillColor: 'rgba(220,220,220,0.2)',
        strokeColor: 'rgba(220,220,220,1)',
        data: arrayOfArrays[1]
      },
      {
        fillColor: 'rgba(151,187,205,0.2)',
        strokeColor: 'rgba(151,187,205,1)',
        data: arrayOfArrays[2]
      }
    ]
  };
  var Chart;
  var getChart = document.getElementById('canvas').getContext('2d');
  new Chart(getChart).Bar(data);
  console.log('I am here');
}
<commit_msg>removed the var newChart and fixed the graph<commit_after>'use strict';

var imagesArray = [];

function Image(productName, filePath) {
  this.productName = productName;
  this.filePath = filePath;
  this.numClicks = 0;
  this.timesDisplayed = 0;
  imagesArray.push(this);
}
var bagImage = new Image('bag','bag.jpg');
var bananaImage = new Image('banana', 'banana.jpg');
var bootsImage = new Image('boots', 'boots.jpg');
var chairImage = new Image('chair', 'chair.jpg');
var cthulhuImage = new Image('cthulhu', 'cthulhu.jpg');
var dragonImage = new Image('dragon', 'dragon.jpg');
var penImage = new Image('pen', 'pen.jpg');
var scissorsImage = new Image('scissors', 'scissors.jpg');
var sharkImage = new Image('shark', 'shark.jpg');
var sweepImage = new Image('sweep', 'sweep.png');
var unicornImage = new Image('unicorn', 'unicorn.jpg');
var usbImage = new Image('usb', 'usb.gif');
var water_canImage = new Image('water_can', 'water-can.jpg');// BEWARE: underscore vs. dash
var wine_glassImage = new Image('wine_glass', 'wine-glass.jpg');

var image1 = document.getElementById('image1');
var image2 = document.getElementById('image2');
var image3 = document.getElementById('image3');
var randomNumber1 = 0;
var randomNumber2 = 0;
var randomNumber3 = 0;
var globalClickTracker = 0;

var arrayOfArrays = [[],[],[]];

function getThreeImages() {
  getRandomImage1();
  getRandomImage2();
  getRandomImage3();
  duplicatePreventer();
}
function duplicatePreventer() {
  while (image1.src === image2.src || image1.src === image3.src || image2.src === image3.src){
    getThreeImages();
  }
}
function getRandomImage1() {
  randomNumber1 = Math.floor(Math.random() * imagesArray.length);
  document.getElementById('image1').src= 'images-to-be-used/' +  imagesArray[randomNumber1].filePath;
}
function getRandomImage2() {
  randomNumber2 = Math.floor(Math.random() * imagesArray.length);
  document.getElementById('image2').src= 'images-to-be-used/' +  imagesArray[randomNumber2].filePath;
}
function getRandomImage3() {
  randomNumber3 = Math.floor(Math.random() * imagesArray.length);
  document.getElementById('image3').src= 'images-to-be-used/' +  imagesArray[randomNumber3].filePath;
}

var button = document.getElementById('loadButton');

var image1Clicks = 0;
var image2Clicks = 0;
var image3Clicks = 0;

function handleClickOnFirst() {
  imagesArray[randomNumber1].timesDisplayed += 1;
  globalClickTracker += 1;
  if (globalClickTracker === 15) {
    button.removeAttribute('hidden');
  }
  imagesArray[randomNumber1].numClicks += 1;
  getThreeImages();
}
function handleClickOnSecond() {
  imagesArray[randomNumber2].timesDisplayed += 1;
  globalClickTracker += 1;
  if (globalClickTracker === 15) {
    button.removeAttribute('hidden');
  }
  imagesArray[randomNumber2].numClicks += 1;
  getThreeImages();
}
function handleClickOnThird() {
  imagesArray[randomNumber3].timesDisplayed += 1;
  globalClickTracker += 1;
  if (globalClickTracker === 15) {
    button.removeAttribute('hidden');
  }
  imagesArray[randomNumber3].numClicks += 1;
  getThreeImages();
}

image1.addEventListener('click', handleClickOnFirst);
image2.addEventListener('click', handleClickOnSecond);
image3.addEventListener('click', handleClickOnThird);
button.addEventListener('click', handleButton);
getThreeImages();

function handleButton() {
  for (var i = 0; i < imagesArray.length; i++) {
  }
  makeChart();
}
function makeChart() {
  for (var i = 0; i < imagesArray.length; i++) {
    arrayOfArrays[0][i] = imagesArray[i].productName;
    arrayOfArrays[1][i] = imagesArray[i].numClicks;
    arrayOfArrays[2][i] = imagesArray[i].timesDisplayed;
  }
  var data = {
    labels: ['bag', 'banana', 'chair', 'cthulhu', 'dragon', 'pen', 'scissors', 'shark', 'sweep', 'unicorn', 'usb', 'water_can', 'wine_glass'],
    datasets: [
      {
        fillColor: 'rgba(220,220,220,0.2)',
        strokeColor: 'rgba(220,220,220,1)',
        data: arrayOfArrays[1]
      },
      {
        fillColor: 'rgba(151,187,205,0.2)',
        strokeColor: 'rgba(151,187,205,1)',
        data: arrayOfArrays[2]
      }
    ]
  };
  // var Chart;
  var getChart = document.getElementById('canvas').getContext('2d');
  new Chart(getChart).Bar(data);
  console.log('I am here');
}
<|endoftext|>