<commit_before>/* global Gallery */
(function ($, Gallery) {
	"use strict";
	/**
	 * Stores the gallery configuration
	 *
	 * @param {{features: string[], mediatypes: string[]}} config
	 * @constructor
	 */
	var Config = function (config) {
		this.galleryFeatures = this._setGalleryFeatures(config.features);
		this.mediaTypes = this._setMediaTypes(config.mediatypes);
	};

	Config.prototype = {
		galleryFeatures: [],
		mediaTypes: [],
		cachedMediaTypesString: '',
		albumPermissions: null,
		albumInfo: null,
		albumSorting: null,
		albumError: false,
		infoLoaded: false,

		/**
		 * Returns the list of supported media types in a string
		 *
		 * @returns {string}
		 */
		getMediaTypes: function () {
			return this.cachedMediaTypesString;
		},

		/**
		 * Stores the configuration about the current album
		 *
		 * @param {{
		 * 	fileid: number,
		 * 	permissions: number,
		 * 	path: string,
		 * 	etag: string
		 * 	information,
		 * 	sorting,
		 * 	error: string
		 * }} albumConfig
		 */
		setAlbumConfig: function (albumConfig) {
			this.albumPermissions = this._setAlbumPermissions(albumConfig);
			this.albumInfo = this._setAlbumInfo(albumConfig);
			this.albumSorting = this._setAlbumSorting(albumConfig);
			this.albumError = albumConfig.error;
		},

		/**
		 * Updates the sorting order
		 */
		updateAlbumSorting: function (sortConfig) {
			this.albumSorting = {
				type: sortConfig.type,
				order: sortConfig.order,
				albumOrder: sortConfig.albumOrder
			};
		},

		/**
		 * Saves the list of features which have been enabled in the app
		 *
		 * @param {string[]} configFeatures
		 *
		 * @returns {Array}
		 * @private
		 */
		_setGalleryFeatures: function (configFeatures) {
			var features = [];
			var feature = null;
			if (!$.isEmptyObject(configFeatures)) {
				for (var i = 0, keys = Object.keys(configFeatures); i < keys.length; i++) {
					feature = keys[i];
					if (this._validateFeature(feature)) {
						features.push(feature);
					}
				}
			}

			return features;
		},

		/**
		 * Saves the list of supported media types
		 *
		 * @param {string[]} mediaTypes
		 *
		 * @returns {Array}
		 * @private
		 */
		_setMediaTypes: function (mediaTypes) {
			var supportedMediaTypes = [];
			var mediaType = null;
			var i, mediaTypesLength = mediaTypes.length;
			if (mediaTypesLength) {
				for (i = 0; i < mediaTypesLength; i++) {
					mediaType = mediaTypes[i];
					if (this._validateMediaType(mediaType)) {
						supportedMediaTypes.push(mediaType);
					}
				}
			}
			this.cachedMediaTypesString = supportedMediaTypes.join(';');

			return supportedMediaTypes;
		},

		/**
		 * Determines if we can accept the feature in this browser environment
		 *
		 * @param {string} feature
		 *
		 * @returns {boolean}
		 * @private
		 */
		_validateFeature: function (feature) {
			var isAcceptable = true;
			if (feature === 'native_svg' && Gallery.ieVersion !== false) {
				isAcceptable = false;
			}

			return isAcceptable;
		},

		/**
		 * Determines if we can accept the media type in this browser environment
		 *
		 * @param {string} mediaType
		 *
		 * @returns {boolean}
		 * @private
		 */
		_validateMediaType: function (mediaType) {
			var isAcceptable = true;
			if (mediaType === 'image/svg+xml' && Gallery.ieVersion !== false) {
				isAcceptable = false;
			}

			return isAcceptable;
		},

		/**
		 * Saves the permissions for the current album
		 *
		 * @param {{
		 * 	fileid: number,
		 * 	permissions: number,
		 * 	path: string,
		 * 	etag: string
		 * 	information,
		 * 	sorting,
		 * 	error: string
		 * }} albumConfig
		 *
		 * @returns {{fileid: number, permissions: number}}
		 * @private
		 */
		_setAlbumPermissions: function (albumConfig) {
			return {
				fileid: albumConfig.fileid,
				permissions: albumConfig.permissions
			};
		},

		/**
		 * Saves the description and copyright information for the current album
		 *
		 * @param {{
		 * 	fileid: number,
		 * 	permissions: number,
		 * 	path: string,
		 * 	etag: string
		 * 	information,
		 * 	sorting,
		 * 	error: string
		 * }} albumConfig
		 *
		 * @returns {null||{
		 * 	description: string,
		 * 	descriptionLink: string,
		 * 	copyright: string,
		 * 	copyrightLink: string,
		 * 	background: string,
		 * 	filePath: string,
		 * 	inherit: bool,
		 * 	level: number
		 * }}
		 * @private
		 */
		_setAlbumInfo: function (albumConfig) {
			var albumPath = albumConfig.path;

			/**@type {{
			 * 	description: string,
			 * 	description_link: string,
			 * 	copyright: string,
			 * 	copyright_link: string,
			 * 	background: string,
			 * 	inherit: bool,
			 * 	level: number
			 * }}
			 */
			var albumInfo = albumConfig.information;
			var params = null;
			if (!$.isEmptyObject(albumInfo)) {
				var docPath = albumPath;
				var level = albumInfo.level;
				if (level > 0) {
					if (docPath.indexOf('/') !== -1) {
						var folders = docPath.split('/');
						folders = folders.slice(-0, -level);
						docPath = folders.join('/') + '/';
					} else {
						docPath = '';
					}
				}

				/* jshint camelcase: false */
				params = {
					description: albumInfo.description,
					descriptionLink: albumInfo.description_link,
					copyright: albumInfo.copyright,
					copyrightLink: albumInfo.copyright_link,
					background: albumInfo.background,
					filePath: docPath,
					inherit: albumInfo.inherit,
					level: albumInfo.level
				};
			}

			return params;
		},

		/**
		 * Saves the sorting configuration for the current album
		 *
		 * @param {{
		 * 	fileid: number,
		 * 	permissions: number,
		 * 	path: string,
		 * 	etag: string
		 * 	information,
		 * 	sorting,
		 * 	error: string
		 * }} albumConfig
		 *
		 * @returns {{type: string, order: string, albumOrder: string}}
		 * @private
		 */
		_setAlbumSorting: function (albumConfig) {
			var sortType = 'name';
			var sortOrder = 'asc';
			var albumSortOrder = 'asc';
			if (!$.isEmptyObject(albumConfig.sorting)) {
				if (!$.isEmptyObject(albumConfig.sorting.type)) {
					sortType = albumConfig.sorting.type;
				}
				if (!$.isEmptyObject(albumConfig.sorting.order)) {
					sortOrder = albumConfig.sorting.order;
					if (sortType === 'name') {
						albumSortOrder = sortOrder;
					}
				}
			}

			return {
				type: sortType,
				order: sortOrder,
				albumOrder: albumSortOrder
			};
		}
	};

	Gallery.Config = Config;
})(jQuery, Gallery);
<commit_msg>Simplify JS env check<commit_after>/* global Gallery */
(function ($, Gallery) {
	"use strict";
	/**
	 * Stores the gallery configuration
	 *
	 * @param {{features: string[], mediatypes: string[]}} config
	 * @constructor
	 */
	var Config = function (config) {
		this.galleryFeatures = this._setGalleryFeatures(config.features);
		this.mediaTypes = this._setMediaTypes(config.mediatypes);
	};

	Config.prototype = {
		galleryFeatures: [],
		mediaTypes: [],
		cachedMediaTypesString: '',
		albumPermissions: null,
		albumInfo: null,
		albumSorting: null,
		albumError: false,
		infoLoaded: false,

		/**
		 * Returns the list of supported media types in a string
		 *
		 * @returns {string}
		 */
		getMediaTypes: function () {
			return this.cachedMediaTypesString;
		},

		/**
		 * Stores the configuration about the current album
		 *
		 * @param {{
		 * 	fileid: number,
		 * 	permissions: number,
		 * 	path: string,
		 * 	etag: string
		 * 	information,
		 * 	sorting,
		 * 	error: string
		 * }} albumConfig
		 */
		setAlbumConfig: function (albumConfig) {
			this.albumPermissions = this._setAlbumPermissions(albumConfig);
			this.albumInfo = this._setAlbumInfo(albumConfig);
			this.albumSorting = this._setAlbumSorting(albumConfig);
			this.albumError = albumConfig.error;
		},

		/**
		 * Updates the sorting order
		 */
		updateAlbumSorting: function (sortConfig) {
			this.albumSorting = {
				type: sortConfig.type,
				order: sortConfig.order,
				albumOrder: sortConfig.albumOrder
			};
		},

		/**
		 * Saves the list of features which have been enabled in the app
		 *
		 * @param {string[]} configFeatures
		 *
		 * @returns {Array}
		 * @private
		 */
		_setGalleryFeatures: function (configFeatures) {
			var features = [];
			var feature = null;
			if (!$.isEmptyObject(configFeatures)) {
				for (var i = 0, keys = Object.keys(configFeatures); i < keys.length; i++) {
					feature = keys[i];
					if (this._worksInCurrentBrowser(feature, 'native_svg')) {
						features.push(feature);
					}
				}
			}

			return features;
		},

		/**
		 * Saves the list of supported media types
		 *
		 * @param {string[]} mediaTypes
		 *
		 * @returns {Array}
		 * @private
		 */
		_setMediaTypes: function (mediaTypes) {
			var supportedMediaTypes = [];
			var mediaType = null;
			var i, mediaTypesLength = mediaTypes.length;
			if (mediaTypesLength) {
				for (i = 0; i < mediaTypesLength; i++) {
					mediaType = mediaTypes[i];
					if (this._worksInCurrentBrowser(mediaType, 'image/svg+xml')) {
						supportedMediaTypes.push(mediaType);
					}
				}
			}
			this.cachedMediaTypesString = supportedMediaTypes.join(';');

			return supportedMediaTypes;
		},

		/**
		 * Determines if we can accept a specific config element in Internet Explorer
		 *
		 * @param {string} feature
		 * @param {string} validationRule
		 *
		 * @returns {boolean}
		 * @private
		 */
		_worksInCurrentBrowser: function (feature, validationRule) {
			var isAcceptable = true;
			if (feature === validationRule && Gallery.ieVersion !== false) {
				isAcceptable = false;
			}

			return isAcceptable;
		},

		/**
		 * Saves the permissions for the current album
		 *
		 * @param {{
		 * 	fileid: number,
		 * 	permissions: number,
		 * 	path: string,
		 * 	etag: string
		 * 	information,
		 * 	sorting,
		 * 	error: string
		 * }} albumConfig
		 *
		 * @returns {{fileid: number, permissions: number}}
		 * @private
		 */
		_setAlbumPermissions: function (albumConfig) {
			return {
				fileid: albumConfig.fileid,
				permissions: albumConfig.permissions
			};
		},

		/**
		 * Saves the description and copyright information for the current album
		 *
		 * @param {{
		 * 	fileid: number,
		 * 	permissions: number,
		 * 	path: string,
		 * 	etag: string
		 * 	information,
		 * 	sorting,
		 * 	error: string
		 * }} albumConfig
		 *
		 * @returns {null||{
		 * 	description: string,
		 * 	descriptionLink: string,
		 * 	copyright: string,
		 * 	copyrightLink: string,
		 * 	background: string,
		 * 	filePath: string,
		 * 	inherit: bool,
		 * 	level: number
		 * }}
		 * @private
		 */
		_setAlbumInfo: function (albumConfig) {
			var albumPath = albumConfig.path;

			/**@type {{
			 * 	description: string,
			 * 	description_link: string,
			 * 	copyright: string,
			 * 	copyright_link: string,
			 * 	background: string,
			 * 	inherit: bool,
			 * 	level: number
			 * }}
			 */
			var albumInfo = albumConfig.information;
			var params = null;
			if (!$.isEmptyObject(albumInfo)) {
				var docPath = albumPath;
				var level = albumInfo.level;
				if (level > 0) {
					if (docPath.indexOf('/') !== -1) {
						var folders = docPath.split('/');
						folders = folders.slice(-0, -level);
						docPath = folders.join('/') + '/';
					} else {
						docPath = '';
					}
				}

				/* jshint camelcase: false */
				params = {
					description: albumInfo.description,
					descriptionLink: albumInfo.description_link,
					copyright: albumInfo.copyright,
					copyrightLink: albumInfo.copyright_link,
					background: albumInfo.background,
					filePath: docPath,
					inherit: albumInfo.inherit,
					level: albumInfo.level
				};
			}

			return params;
		},

		/**
		 * Saves the sorting configuration for the current album
		 *
		 * @param {{
		 * 	fileid: number,
		 * 	permissions: number,
		 * 	path: string,
		 * 	etag: string
		 * 	information,
		 * 	sorting,
		 * 	error: string
		 * }} albumConfig
		 *
		 * @returns {{type: string, order: string, albumOrder: string}}
		 * @private
		 */
		_setAlbumSorting: function (albumConfig) {
			var sortType = 'name';
			var sortOrder = 'asc';
			var albumSortOrder = 'asc';
			if (!$.isEmptyObject(albumConfig.sorting)) {
				if (!$.isEmptyObject(albumConfig.sorting.type)) {
					sortType = albumConfig.sorting.type;
				}
				if (!$.isEmptyObject(albumConfig.sorting.order)) {
					sortOrder = albumConfig.sorting.order;
					if (sortType === 'name') {
						albumSortOrder = sortOrder;
					}
				}
			}

			return {
				type: sortType,
				order: sortOrder,
				albumOrder: albumSortOrder
			};
		}
	};

	Gallery.Config = Config;
})(jQuery, Gallery);
<|endoftext|>


<commit_before>var Google_Loader = (function (window, document) {

    that = this;

	Google_Loader = function (opts) {

        this.int_loading_state = 0;

        this.current_loop = 0;

    	this.fn_loading_screen_animation();

		window.addEventListener('load', function() {
		    FastClick.attach(document.body);
		}, false);

		$('.replay-message-button').on('click', this.fn_replay.bind(this));

	};

	Google_Loader.prototype = {

		// ------------------------------------------------------
		// Skimmin Core Functions
		// ------------------------------------------------------

        fn_replay: function() {

        	$('.replay-message-button').removeClass('animated bounceIn');
        	$('.replay-message-button').addClass('animated rotateOut');

        	setTimeout(function() {
        		$('.replay-message-button').fadeOut(0);
        		$('.replay-message-button').removeClass('animated rotateOut');
        	}, 500);

        	loading_circles = '
' +
					'

' +
					'

' +
				'
' +
				'
' +
					'

' +
					'

' +
				'
' +
				'
' +
					'

' +
					'

' +
				'
' +
				'
' +
					'

' +
					'

' +
				'
';

        	$('#loading-container').fadeIn(0);
        	$('#loading-circles-container').fadeIn(0);
        	$('#loading-circles-container').html('');
        	$('#loading-circles-container').html(loading_circles);

        	this.fn_loading_screen_animation();

        },

        // one full "loop"  -- this function is called in another, high level loading function
        fn_loading_screen_animation: function(int_degrees) {

            if (this.current_loop == 0) {

            	setTimeout(function() {
            		$('#loading-inner-circle-1').fadeIn(0);
            		$('#loading-inner-circle-1').addClass('animated bounceIn');
            	}, 1000);

            	setTimeout(function() {
            		$('#loading-inner-circle-2').fadeIn(0);
            		$('#loading-inner-circle-2').addClass('animated bounceIn');
            	}, 1500);

            	setTimeout(function() {
            		$('#loading-inner-circle-3').fadeIn(0);
            		$('#loading-inner-circle-3').addClass('animated bounceIn');
            	}, 2000);

                setTimeout(function() {
                	$('#loading-inner-circle-4').fadeIn(0);
            		$('#loading-inner-circle-4').addClass('animated bounceIn');
            	}, 2500);

            }

            else {

            	$('#loading-circle-1').fadeIn(0);
            	$('#loading-circle-1').addClass('animated zoomIn');

            	setTimeout(function() {
            		$('#loading-circle-2').fadeIn(0);
            		$('#loading-circle-2').addClass('animated zoomIn');
            	}, 75);

            	setTimeout(function() {
            		$('#loading-circle-3').fadeIn(0);
            		$('#loading-circle-3').addClass('animated zoomIn');
            	}, 150);

            	setTimeout(function() {
            		$('#loading-circle-4').fadeIn(0);
            		$('#loading-circle-4').addClass('animated zoomIn');
            	}, 225);

            	setTimeout(function() {
            		$('#loading-circle-1').removeClass('animated zoomIn');
            		$('#loading-circle-2').removeClass('animated zoomIn');
            		$('#loading-circle-3').removeClass('animated zoomIn');
            		$('#loading-circle-4').removeClass('animated zoomIn');
            	}, 1000);

            	setTimeout(function() {
        			$('#loading-inner-circle-1').fadeIn(0);
        			$('#loading-inner-circle-1').addClass('animated bounceIn');
        		}, 1225);

           		setTimeout(function() {
        			$('#loading-inner-circle-2').fadeIn(0);
        			$('#loading-inner-circle-2').addClass('animated bounceIn');
        		}, 1725);

            	setTimeout(function() {
        			$('#loading-inner-circle-3').fadeIn(0);
        			$('#loading-inner-circle-3').addClass('animated bounceIn');
        		}, 2225);

            	setTimeout(function() {
        			$('#loading-inner-circle-4').fadeIn(0);
        			$('#loading-inner-circle-4').addClass('animated bounceIn');
        		}, 2725);

            }

            setTimeout(function() {
        		$('#loading-circle-1').addClass('animated bounceOut');
        		$('#loading-circle-2').addClass('animated bounceOut');
    			$('#loading-circle-3').addClass('animated bounceOut');
        		$('#loading-circle-4').addClass('animated bounceOut');
        	}, 3175);

        	setTimeout(function() {
        		$('.replay-message-button').fadeIn(0);
        		$('.replay-message-button').addClass('animated bounceIn');
        		$('#loading-container').fadeOut(500);
        	}, 3800);

        	/*setTimeout(function(){
        		$('.replay-message-button').fadeOut(0);
        		$('.replay-message-button').removeClass('animated bounceIn');
        	}, 4600);*/

            setTimeout(function() {
        		$('#loading-inner-circle-1').fadeOut(0);
    			$('#loading-inner-circle-2').fadeOut(0);
    			$('#loading-inner-circle-3').fadeOut(0);
        		$('#loading-inner-circle-4').fadeOut(0);
            	$('#loading-circles-container').fadeOut(0);

        		$('#loading-inner-circle-1').fadeOut(0);
        		$('#loading-inner-circle-1').removeClass('animated bounceIn');
        		$('#loading-inner-circle-2').fadeOut(0);
        		$('#loading-inner-circle-2').removeClass('animated bounceIn');
        		$('#loading-inner-circle-3').fadeOut(0);
        		$('#loading-inner-circle-3').removeClass('animated bounceIn');
        		$('#loading-inner-circle-4').fadeOut(0);
        		$('#loading-inner-circle-4').removeClass('animated bounceIn');

        	}, 5125);

            this.current_loop += 1;

        },

	};

	return Google_Loader;

})(window, document);
<commit_msg>Update google-loader.js<commit_after>var Google_Loader = (function (window, document) {

    that = this;

	Google_Loader = function (opts) {

        this.int_loading_state = 0;

        this.current_loop = 0;

    	this.fn_loading_screen_animation();

		window.addEventListener('load', function() {
		    FastClick.attach(document.body);
		}, false);

		$('.replay-message-button').on('click', this.fn_replay.bind(this));

	};

	Google_Loader.prototype = {

		// ------------------------------------------------------
		// Skimmin Core Functions
		// ------------------------------------------------------

        fn_replay: function() {

        	$('.replay-message-button').removeClass('animated bounceIn');
        	$('.replay-message-button').addClass('animated rotateOut');

        	setTimeout(function() {
        		$('.replay-message-button').fadeOut(0);
        		$('.replay-message-button').removeClass('animated rotateOut');
        	}, 500);

        	loading_circles = '
' +
					'

' +
					'

' +
				'
' +
				'
' +
					'

' +
					'

' +
				'
' +
				'
' +
					'

' +
					'

' +
				'
' +
				'
' +
					'

' +
					'

' +
				'
';

        	$('#loading-container').fadeIn(0);
        	$('#loading-circles-container').fadeIn(0);
        	$('#loading-circles-container').html('');
        	$('#loading-circles-container').html(loading_circles);

        	this.fn_loading_screen_animation();

        },

        // one full "loop"  -- this function is called in another, high level loading function
        fn_loading_screen_animation: function(int_degrees) {

            if (this.current_loop == 0) {

            	setTimeout(function() {
            		$('#loading-inner-circle-1').fadeIn(0);
            		$('#loading-inner-circle-1').addClass('animated bounceIn');
            	}, 1000);

            	setTimeout(function() {
            		$('#loading-inner-circle-2').fadeIn(0);
            		$('#loading-inner-circle-2').addClass('animated bounceIn');
            	}, 1500);

            	setTimeout(function() {
            		$('#loading-inner-circle-3').fadeIn(0);
            		$('#loading-inner-circle-3').addClass('animated bounceIn');
            	}, 2000);

                setTimeout(function() {
                	$('#loading-inner-circle-4').fadeIn(0);
            		$('#loading-inner-circle-4').addClass('animated bounceIn');
            	}, 2500);

            }

            else {

            	$('#loading-circle-1').fadeIn(0);
            	$('#loading-circle-1').addClass('animated zoomIn');

            	setTimeout(function() {
            		$('#loading-circle-2').fadeIn(0);
            		$('#loading-circle-2').addClass('animated zoomIn');
            	}, 75);

            	setTimeout(function() {
            		$('#loading-circle-3').fadeIn(0);
            		$('#loading-circle-3').addClass('animated zoomIn');
            	}, 150);

            	setTimeout(function() {
            		$('#loading-circle-4').fadeIn(0);
            		$('#loading-circle-4').addClass('animated zoomIn');
            	}, 225);

            	setTimeout(function() {
            		$('#loading-circle-1').removeClass('animated zoomIn');
            		$('#loading-circle-2').removeClass('animated zoomIn');
            		$('#loading-circle-3').removeClass('animated zoomIn');
            		$('#loading-circle-4').removeClass('animated zoomIn');
            	}, 1000);

            	setTimeout(function() {
        			$('#loading-inner-circle-1').fadeIn(0);
        			$('#loading-inner-circle-1').addClass('animated bounceIn');
        		}, 1225);

           		setTimeout(function() {
        			$('#loading-inner-circle-2').fadeIn(0);
        			$('#loading-inner-circle-2').addClass('animated bounceIn');
        		}, 1725);

            	setTimeout(function() {
        			$('#loading-inner-circle-3').fadeIn(0);
        			$('#loading-inner-circle-3').addClass('animated bounceIn');
        		}, 2225);

            	setTimeout(function() {
        			$('#loading-inner-circle-4').fadeIn(0);
        			$('#loading-inner-circle-4').addClass('animated bounceIn');
        		}, 2725);

            }

            setTimeout(function() {
        		$('#loading-circle-1').addClass('animated bounceOut');
        		$('#loading-circle-2').addClass('animated bounceOut');
    			$('#loading-circle-3').addClass('animated bounceOut');
        		$('#loading-circle-4').addClass('animated bounceOut');
        	}, 3175);

        	setTimeout(function() {
        		$('.replay-message-button').fadeIn(0);
        		$('.replay-message-button').addClass('animated bounceIn');
        		$('#loading-container').fadeOut(500);
        	}, 3800);

        	// spin the colored circles, while removing the small white ones
        	setTimeout(function() {
            		$('#loading-inner-circle-1').removeClass('animated bounceIn');
                	$('#loading-circle-1').css('-webkit-transform', 'rotateY(-' + '180' + 'deg)');
                	setTimeout(function() {
                		$('#loading-inner-circle-1').fadeOut(30);
                		$('#loading-inner-circle-1').removeClass('animated bounceIn')
            		}, 260);
            	}, 3700);

        	setTimeout(function() {
            		$('#loading-inner-circle-2').removeClass('animated bounceIn');
               		$('#loading-circle-2').css('-webkit-transform', 'rotateY(-' + '180' + 'deg)');
                	setTimeout(function() {
                		$('#loading-inner-circle-2').fadeOut(30);
            		}, 260);
        	}, 4200);

            	setTimeout(function() {
            		$('#loading-inner-circle-3').removeClass('animated bounceIn');
                	$('#loading-circle-3').css('-webkit-transform', 'rotateY(-' + '180' + 'deg)');
                	setTimeout(function() {
                		$('#loading-inner-circle-3').fadeOut(30);
            		}, 260);
        	}, 4700);

            	setTimeout(function() {
            		$('#loading-inner-circle-4').removeClass('animated bounceIn');
                	$('#loading-circle-4').css('-webkit-transform', 'rotateY(-' + '180' + 'deg)');
                	setTimeout(function() {
                		$('#loading-inner-circle-4').fadeOut(30);
            		}, 260);
            	}, 5200);

            setTimeout(function() {
        		$('#loading-inner-circle-1').fadeOut(0);
    			$('#loading-inner-circle-2').fadeOut(0);
    			$('#loading-inner-circle-3').fadeOut(0);
        		$('#loading-inner-circle-4').fadeOut(0);
            		$('#loading-circles-container').fadeOut(0);

        		$('#loading-inner-circle-1').fadeOut(0);
        		$('#loading-inner-circle-1').removeClass('animated bounceIn');
        		$('#loading-inner-circle-2').fadeOut(0);
        		$('#loading-inner-circle-2').removeClass('animated bounceIn');
        		$('#loading-inner-circle-3').fadeOut(0);
        		$('#loading-inner-circle-3').removeClass('animated bounceIn');
        		$('#loading-inner-circle-4').fadeOut(0);
        		$('#loading-inner-circle-4').removeClass('animated bounceIn');

        	}, 5125);

            this.current_loop += 1;

        },

	};

	return Google_Loader;

})(window, document);
<|endoftext|>


<commit_before>;(function($){
/*
**
 * jqGrid addons using jQuery UI
 * Author: Mark Williams
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * depends on jQuery UI sortable
**/
if ($.browser.msie && $.browser.version==8) {
	$.expr[":"].hidden = function(elem) {
		return elem.offsetWidth === 0 || elem.offsetHeight === 0 ||
			elem.style.display == "none";
	}
}

$.jgrid.extend({
	sortableColumns : function (tblrow)
	{
		return this.each(function (){
			ts = this;
			function start() {ts.p.disableClick = true;};
			var sortable_opts = {
				"tolerance" : "pointer",
				"axis" : "x",
				"items": '>th:not(:has(#jqgh_cb,#jqgh_rn,#jqgh_subgrid),:hidden)',
				"placeholder": {
					element: function(item) {
						var el = $(document.createElement(item[0].nodeName))
						.addClass(item[0].className+" ui-sortable-placeholder ui-state-highlight")
						.removeClass("ui-sortable-helper")[0];
						return el;
					},
					update: function(self, p) {
						p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10));
						p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10));
					}
				},
				"update": function(event, ui) {
					var p = $(ui.item).parent();
					var th = $(">th", p);
					var colModel = ts.p.colModel;
					var cmMap = {};
					$.each(colModel, function(i) { cmMap[this.name]=i });
					var permutation = [];
					th.each(function(i) {
						var id = $(">div", this).get(0).id.replace(/^jqgh_/, "");
							if (id in cmMap) {
								permutation.push(cmMap[id]);
							}
					});

					$(ts).jqGrid("remapColumns",permutation, true, true);
					if ($.isFunction(ts.p.sortable.update)) {
						ts.p.sortable.update(permutation);
					}
					setTimeout(function(){ts.p.disableClick=false}, 50);
				}
			};
			if (ts.p.sortable.options) {
				$.extend(sortable_opts, ts.p.sortable.options);
			} else if ($.isFunction(ts.p.sortable)) {
				ts.p.sortable = { "update" : ts.p.sortable };
			}
			if (sortable_opts.start) {
				var s = sortable_opts.start;
				sortable_opts.start = function(e,ui) {
					start();
					s.call(this,e,ui);
				}
			} else {
				sortable_opts.start = start;
			}
			if (ts.p.sortable.exclude) {
				sortable_opts.items += ":not("+ts.p.sortable.exclude+")";
			}
			tblrow.sortable(sortable_opts).data("sortable").floating = true;
		});
	},
    columnChooser : function(opts) {
        var self = this;
        var selector = $('

<select multiple="multiple"></select>

');
        var select = $('select', selector);

        opts = $.extend({
            "title" : "Select columns",
            "width" : 420,
            "height" : 240,
            "classname" : null,
            "done" : function(perm) { if (perm) self.jqGrid("remapColumns", perm, true) },
            "ok" : "Ok",
            "cancel" : "Cancel",
            /* msel is either the name of a ui widget class that
               extends a multiselect, or a function that supports
               creating a multiselect object (with no argument,
               or when passed an object), and destroying it (when
               passed the string "destroy"). */
            "msel" : "multiselect",
            /* "msel_opts" : {}, */

            /* dlog is either the name of a ui widget class that
               behaves in a dialog-like way, or a function, that
               supports creating a dialog (when passed dlog_opts)
               or destroying a dialog (when passed the string
               "destroy")
               */
            "dlog" : "dialog",

            /* dlog_opts is either an option object to be passed
               to "dlog", or (more likely) a function that creates
               the options object.
               The default produces a suitable options object for
               ui.dialog */
            "dlog_opts" : function(opts) {
                var buttons = {};
                buttons[opts.ok] = function() {
                    opts.apply_perm();
                    opts.cleanup(false);
                };
                buttons[opts.cancel] = function() {
                    opts.cleanup(true);
                };
                return {
                    "buttons": buttons,
                    "close": function() {
                        opts.cleanup(true);
                    },
                    "resizable": false,
                    "width": opts.width+20
                };
            },
            /* Function to get the permutation array, and pass it to the
               "done" function */
            "apply_perm" : function() {
                $('option',select).each(function(i) {
                    if (this.selected) {
                        self.jqGrid("showCol", colModel[this.value].name);
                    } else {
                        self.jqGrid("hideCol", colModel[this.value].name);
                    }
                });

                var perm = fixedCols.slice(0);
                $('option[selected]',select).each(function() { perm.push(parseInt(this.value)) });
                $.each(perm, function() { delete colMap[colModel[this].name] });
                $.each(colMap, function() { perm.push(this) });
                if (opts.done) {
                    opts.done.call(self, perm);
                }
            },
            /* Function to cleanup the dialog, and select. Also calls the
               done function with no permutation (to indicate that the
               columnChooser was aborted */
            "cleanup" : function(calldone) {
                call(opts.dlog, selector, 'destroy');
                call(opts.msel, select, 'destroy');
                selector.remove();
                if (calldone && opts.done) {
                    opts.done.call(self);
                }
            }
        }, opts || {});

        if (opts.title) {
            selector.attr("title", opts.title);
        }
        if (opts.classname) {
            selector.addClass(classname);
            select.addClass(classname);
        }
        if (opts.width) {
            $(">div",selector).css({"width": opts.width,"margin":"0 auto"});
            select.css("width", opts.width);
        }
        if (opts.height) {
            $(">div",selector).css("height", opts.height);
            select.css("height", opts.height - 10);
        }
        var colModel = self.jqGrid("getGridParam", "colModel");
        var colNames = self.jqGrid("getGridParam", "colNames");
        var colMap = {}, fixedCols = [];

        select.empty();
        $.each(colModel, function(i) {
            colMap[this.name] = i;
            if (this.hidedlg) {
                if (!this.hidden) {
                    fixedCols.push(i);
                }
                return;
            }

            var opt = "<option value='"+i+"'";
            if (!this.hidden) {
                opt += " selected";
            }
            opt += ">"+colNames[i]+"</option>";
            select.append(opt);
        });

        function call(fn, obj) {
            if (!fn) return;
            if (typeof fn == 'string') {
                if ($.fn[fn]) {
                    $.fn[fn].apply(obj, $.makeArray(arguments).slice(2));
                }
            } else if ($.isFunction(fn)) {
                fn.apply(obj, $.makeArray(arguments).slice(2));
            }
        }

        var dopts = $.isFunction(opts.dlog_opts) ? opts.dlog_opts.call(self, opts) : opts.dlog_opts;
        call(opts.dlog, selector, dopts);
        var mopts = $.isFunction(opts.msel_opts) ? opts.msel_opts.call(self, opts) : opts.msel_opts;
        call(opts.msel, select, opts.msel_opts);
    }
})
})(jQuery);<commit_msg>Fix in columnChooser. The hidden fields should be added at end of the select tag.<commit_after>;(function($){
/*
**
 * jqGrid addons using jQuery UI
 * Author: Mark Williams
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * depends on jQuery UI sortable
**/
if ($.browser.msie && $.browser.version==8) {
	$.expr[":"].hidden = function(elem) {
		return elem.offsetWidth === 0 || elem.offsetHeight === 0 ||
			elem.style.display == "none";
	}
}

$.jgrid.extend({
	sortableColumns : function (tblrow)
	{
		return this.each(function (){
			ts = this;
			function start() {ts.p.disableClick = true;};
			var sortable_opts = {
				"tolerance" : "pointer",
				"axis" : "x",
				"items": '>th:not(:has(#jqgh_cb,#jqgh_rn,#jqgh_subgrid),:hidden)',
				"placeholder": {
					element: function(item) {
						var el = $(document.createElement(item[0].nodeName))
						.addClass(item[0].className+" ui-sortable-placeholder ui-state-highlight")
						.removeClass("ui-sortable-helper")[0];
						return el;
					},
					update: function(self, p) {
						p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10));
						p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10));
					}
				},
				"update": function(event, ui) {
					var p = $(ui.item).parent();
					var th = $(">th", p);
					var colModel = ts.p.colModel;
					var cmMap = {};
					$.each(colModel, function(i) { cmMap[this.name]=i });
					var permutation = [];
					th.each(function(i) {
						var id = $(">div", this).get(0).id.replace(/^jqgh_/, "");
							if (id in cmMap) {
								permutation.push(cmMap[id]);
							}
					});

					$(ts).jqGrid("remapColumns",permutation, true, true);
					if ($.isFunction(ts.p.sortable.update)) {
						ts.p.sortable.update(permutation);
					}
					setTimeout(function(){ts.p.disableClick=false}, 50);
				}
			};
			if (ts.p.sortable.options) {
				$.extend(sortable_opts, ts.p.sortable.options);
			} else if ($.isFunction(ts.p.sortable)) {
				ts.p.sortable = { "update" : ts.p.sortable };
			}
			if (sortable_opts.start) {
				var s = sortable_opts.start;
				sortable_opts.start = function(e,ui) {
					start();
					s.call(this,e,ui);
				}
			} else {
				sortable_opts.start = start;
			}
			if (ts.p.sortable.exclude) {
				sortable_opts.items += ":not("+ts.p.sortable.exclude+")";
			}
			tblrow.sortable(sortable_opts).data("sortable").floating = true;
		});
	},
    columnChooser : function(opts) {
        var self = this;
        var selector = $('

<select multiple="multiple"></select>

');
        var select = $('select', selector);

        opts = $.extend({
            "title" : "Select columns",
            "width" : 420,
            "height" : 240,
            "classname" : null,
            "done" : function(perm) { if (perm) self.jqGrid("remapColumns", perm, true) },
            "ok" : "Ok",
            "cancel" : "Cancel",
            /* msel is either the name of a ui widget class that
               extends a multiselect, or a function that supports
               creating a multiselect object (with no argument,
               or when passed an object), and destroying it (when
               passed the string "destroy"). */
            "msel" : "multiselect",
            /* "msel_opts" : {}, */

            /* dlog is either the name of a ui widget class that
               behaves in a dialog-like way, or a function, that
               supports creating a dialog (when passed dlog_opts)
               or destroying a dialog (when passed the string
               "destroy")
               */
            "dlog" : "dialog",

            /* dlog_opts is either an option object to be passed
               to "dlog", or (more likely) a function that creates
               the options object.
               The default produces a suitable options object for
               ui.dialog */
            "dlog_opts" : function(opts) {
                var buttons = {};
                buttons[opts.ok] = function() {
                    opts.apply_perm();
                    opts.cleanup(false);
                };
                buttons[opts.cancel] = function() {
                    opts.cleanup(true);
                };
                return {
                    "buttons": buttons,
                    "close": function() {
                        opts.cleanup(true);
                    },
                    "resizable": false,
                    "width": opts.width+20
                };
            },
            /* Function to get the permutation array, and pass it to the
               "done" function */
            "apply_perm" : function() {
                $('option',select).each(function(i) {
                    if (this.selected) {
                        self.jqGrid("showCol", colModel[this.value].name);
                    } else {
                        self.jqGrid("hideCol", colModel[this.value].name);
                    }
                });

                var perm = fixedCols.slice(0);
                $('option[selected]',select).each(function() { perm.push(parseInt(this.value)) });
                $.each(perm, function() { delete colMap[colModel[this].name] });
                $.each(colMap, function() { perm.push(this) });
                if (opts.done) {
                    opts.done.call(self, perm);
                }
            },
            /* Function to cleanup the dialog, and select. Also calls the
               done function with no permutation (to indicate that the
               columnChooser was aborted */
            "cleanup" : function(calldone) {
                call(opts.dlog, selector, 'destroy');
                call(opts.msel, select, 'destroy');
                selector.remove();
                if (calldone && opts.done) {
                    opts.done.call(self);
                }
            }
        }, opts || {});

        if (opts.title) {
            selector.attr("title", opts.title);
        }
        if (opts.classname) {
            selector.addClass(classname);
            select.addClass(classname);
        }
        if (opts.width) {
            $(">div",selector).css({"width": opts.width,"margin":"0 auto"});
            select.css("width", opts.width);
        }
        if (opts.height) {
            $(">div",selector).css("height", opts.height);
            select.css("height", opts.height - 10);
        }
        var colModel = self.jqGrid("getGridParam", "colModel");
        var colNames = self.jqGrid("getGridParam", "colNames");
        var colMap = {}, fixedCols = [];

        select.empty(); var opt="";
        $.each(colModel, function(i) {
            colMap[this.name] = i;
            if (this.hidedlg) {
                if (!this.hidden) {
                    fixedCols.push(i);
                }
                return;
            }

            if (!this.hidden) {
                select.append("<option value='"+i+"' selected='selected'>"+colNames[i]+"</option>");
            } else {
                opt += "<option value='"+i+"'>"+colNames[i]+"</option>";
            }
        });
        if(opt) select.append(opt);
        function call(fn, obj) {
            if (!fn) return;
            if (typeof fn == 'string') {
                if ($.fn[fn]) {
                    $.fn[fn].apply(obj, $.makeArray(arguments).slice(2));
                }
            } else if ($.isFunction(fn)) {
                fn.apply(obj, $.makeArray(arguments).slice(2));
            }
        }

        var dopts = $.isFunction(opts.dlog_opts) ? opts.dlog_opts.call(self, opts) : opts.dlog_opts;
        call(opts.dlog, selector, dopts);
        var mopts = $.isFunction(opts.msel_opts) ? opts.msel_opts.call(self, opts) : opts.msel_opts;
        call(opts.msel, select, opts.msel_opts);
    }
})
})(jQuery);<|endoftext|>


<commit_before>iD.Connection = function() {

    var event = d3.dispatch('auth', 'load'),
        url = 'http://www.openstreetmap.org',
        connection = {},
        user = {},
        version,
        keys,
        inflight = {},
        loadedTiles = {},
        oauth = iD.OAuth().url(url);

    function bboxUrl(b) {
        return url + '/api/0.6/map?bbox=' + [b[0][0],b[1][1],b[1][0],b[0][1]];
    }

    function bboxFromAPI(box, tile, callback) {
        function done(err, parsed) {
             loadedTiles[tile.toString()] = true;
             delete inflight[tile.toString()];
             callback(err, parsed);
         }
         inflight[tile.toString()] = loadFromURL(bboxUrl(box), done);
    }

    function loadFromURL(url, callback) {
        function done(dom) {
            return callback(null, parse(dom));
        }
        return d3.xml(url).get().on('load', done);
    }

    function getNodes(obj) {
        var nelems = obj.getElementsByTagName('nd'), nodes = new Array(nelems.length);
        for (var i = 0, l = nelems.length; i < l; i++) {
            nodes[i] = 'n' + nelems[i].attributes.ref.nodeValue;
        }
        return nodes;
    }

    function getTags(obj) {
        var tags = {}, tagelems = obj.getElementsByTagName('tag');
        for (var i = 0, l = tagelems.length; i < l; i++) {
            var item = tagelems[i];
            tags[item.attributes.k.nodeValue] = item.attributes.v.nodeValue;
        }
        return tags;
    }

    function getMembers(obj) {
        var elems = obj.getElementsByTagName('member'),
            members = new Array(elems.length);

        for (var i = 0, l = elems.length; i < l; i++) {
            members[i] = {
                id: elems[i].attributes.type.nodeValue[0] + elems[i].attributes.ref.nodeValue,
                type: elems[i].attributes.type.nodeValue,
                role: elems[i].attributes.role.nodeValue
            };
        }
        return members;
    }

    function objectData(obj) {
        switch(obj.type) {
            case 'node': return nodeData(obj);
            case 'way': return wayData(obj);
            case 'relation': return relationData(obj);
        }
    }

    function nodeData(obj) {
        var o = { type: 'node', tags: getTags(obj) };
        for (var i = 0, l = obj.attributes.length; i < l; i++) {
            o[obj.attributes[i].nodeName] = obj.attributes[i].nodeValue;
        }
        if (o.lon && o.lat) {
            o.loc = [parseFloat(o.lon), parseFloat(o.lat)];
            delete o.lon; delete o.lat;
        }
        o.id = iD.Entity.id.fromOSM('node', o.id);
        return new iD.Node(o);
    }

    function wayData(obj) {
        var o = { type: 'way', nodes: getNodes(obj),
            tags: getTags(obj)
        };
        for (var i = 0, l = obj.attributes.length; i < l; i++) {
            o[obj.attributes[i].nodeName] = obj.attributes[i].nodeValue;
        }
        o.id = iD.Entity.id.fromOSM('way', o.id);
        return new iD.Way(o);
    }

    function relationData(obj) {
        var o = {
            type: 'relation', members: getMembers(obj),
            tags: getTags(obj)
        };
        for (var i = 0, l = obj.attributes.length; i < l; i++) {
            o[obj.attributes[i].nodeName] = obj.attributes[i].nodeValue;
        }
        o.id = iD.Entity.id.fromOSM('relation', o.id);
        return new iD.Relation(o);
    }

    function addWay(o, wparentsOf) {
        for (var i = 0; i < o.nodes.length; i++) {
            if (o.nodes[i]) {
                if (wparentsOf[o.nodes[i]] === undefined) {
                    wparentsOf[o.nodes[i]] = [];
                }
                wparentsOf[o.nodes[i]].push(o.id);
            }
        }
    }

    function addRelation(o, rparentsOf) {
        for (var i = 0; i < o.members.length; i++) {
            if (o.members[i].id) {
                if (rparentsOf[o.members[i].id] === undefined) {
                    rparentsOf[o.members[i].id] = [];
                }
                rparentsOf[o.members[i].id].push(o.id);
            }
        }
    }

    function parse(dom) {
        if (!dom || !dom.childNodes) return new Error('Bad request');
        var root = dom.childNodes[0];
        var entities = {};
        var rparentsOf = {},
            wparentsOf = {};

        var o, l;
        for (i = 0, l = root.childNodes.length; i < l; i++) {
            switch(root.childNodes[i].nodeName) {
                case 'node':
                    o = nodeData(root.childNodes[i]);
                    entities[o.id] = o;
                    break;
                case 'way':
                    o = wayData(root.childNodes[i]);
                    addWay(o, wparentsOf);
                    entities[o.id] = o;
                    break;
                case 'relation':
                    o = relationData(root.childNodes[i]);
                    addRelation(o, rparentsOf);
                    entities[o.id] = o;
                    break;
            }
        }

        var g = iD.Graph(entities);
        var i;

        for (i in wparentsOf) {
            if (entities[i]) {
                g.transient(entities[i], 'parentWays', d3.functor(wparentsOf[i]));
                g.transient(entities[i], 'poi', d3.functor(true));
            }
        }

        for (i in g.entities) {
            if (entities[i].type === 'node') {
                g.transient(entities[i], 'poi', d3.functor(false));
            }
        }

        for (i in rparentsOf) {
            if (entities[i]) g.transient(entities[i],
                'parentRelations', d3.functor(rparentsOf[i]));
        }

        return g;
    }

    function authenticated() {
        return oauth.authenticated();
    }

    // Generate Changeset XML. Returns a string.
    connection.changesetJXON = function(tags) {
        return {
            osm: {
                changeset: {
                    tag: _.map(tags, function(value, key) {
                        return { '@k': key, '@v': value };
                    }),
                    '@version': 0.3,
                    '@generator': 'iD'
                }
            }
        };
    };

    // Generate [osmChange](http://wiki.openstreetmap.org/wiki/OsmChange)
    // XML. Returns a string.
    connection.osmChangeJXON = function(userid, changeset_id, changes) {
        function nest(x, order) {
            var groups = {};
            for (var i = 0; i < x.length; i++) {
                var tagName = Object.keys(x[i])[0];
                if (!groups[tagName]) groups[tagName] = [];
                groups[tagName].push(x[i][tagName]);
            }
            var ordered = {};
            order.forEach(function(o) {
                if (groups[o]) ordered[o] = groups[o];
            });
            return ordered;
        }

        function rep(entity) {
            return entity.asJXON(changeset_id);
        }

        return {
            osmChange: {
                '@version': 0.3,
                '@generator': 'iD',
                'create': nest(changes.created.map(rep), ['node', 'way', 'relation']),
                'modify': nest(changes.modified.map(rep), ['node', 'way', 'relation']),
                'delete': _.extend(nest(changes.deleted.map(rep), ['relation', 'way', 'node']), {'@if-unused': true})
            }
        };
    };

    connection.putChangeset = function(changes, comment, imagery_used, callback) {
        oauth.xhr({
                method: 'PUT',
                path: '/api/0.6/changeset/create',
                options: { header: { 'Content-Type': 'text/xml' } },
                content: JXON.stringify(connection.changesetJXON({
                    imagery_used: imagery_used.join(';'),
                    comment: comment,
                    created_by: 'iD ' + (version || '')
                }))
            }, function (err, changeset_id) {
                if (err) return callback(err);
                oauth.xhr({
                    method: 'POST',
                    path: '/api/0.6/changeset/' + changeset_id + '/upload',
                    options: { header: { 'Content-Type': 'text/xml' } },
                    content: JXON.stringify(connection.osmChangeJXON(user.id, changeset_id, changes))
                }, function (err) {
                    if (err) return callback(err);
                    oauth.xhr({
                        method: 'PUT',
                        path: '/api/0.6/changeset/' + changeset_id + '/close'
                    }, function (err) {
                        callback(err, changeset_id);
                    });
                });
            });
    };

    function userDetails(callback) {
        function done(err, user_details) {
            var u = user_details.getElementsByTagName('user')[0],
                img = u.getElementsByTagName('img'),
                image_url = '';
            if (img && img[0].getAttribute('href')) {
                image_url = img[0].getAttribute('href');
            }
            callback(connection.user({
                display_name: u.attributes.display_name.nodeValue,
                image_url: image_url,
                id: u.attributes.id.nodeValue
            }).user());
        }
        oauth.xhr({ method: 'GET', path: '/api/0.6/user/details' }, done);
    }

    function tileAlreadyLoaded(c) { return !loadedTiles[c.toString()] && !inflight[c.toString()]; }

    function abortRequest(i) { i.abort(); }

    function loadTile(e) {
        function done(err, g) {
            event.load(err, g);
        }
        bboxFromAPI(e.box, e.tile, done);
    }

    function loadTiles(projection, dimensions) {
        var scaleExtent = [16, 16],
            s = projection.scale(),
            tiles = d3.geo.tile()
                .scaleExtent(scaleExtent)
                .scale(s)
                .size(dimensions)
                .translate(projection.translate())(),
            z = Math.max(Math.log(s) / Math.log(2) - 8, 0),
            rz = Math.max(scaleExtent[0], Math.min(scaleExtent[1], Math.floor(z))),
            ts = 256 * Math.pow(2, z - rz),
            tile_origin = [
                s / 2 - projection.translate()[0],
                s / 2 - projection.translate()[1]];

        function apiExtentBox(c) {
            var x = (c[0] * ts) - tile_origin[0];
            var y = (c[1] * ts) - tile_origin[1];
            return {
                box: [
                    projection.invert([x, y]),
                    projection.invert([x + ts, y + ts])],
                tile: c
            };
        }

        _.filter(inflight, function(v, i) {
            var wanted = _.find(tiles, function(tile) {
                return i === tile.toString();
            });
            if (!wanted) delete inflight[i];
            return !wanted;
        }).map(abortRequest);

        tiles
            .filter(tileAlreadyLoaded)
            .map(apiExtentBox)
            .forEach(loadTile);
    }

    connection.userUrl = function(username) {
        return url + "/user/" + username;
    };

    connection.url = function(_) {
        if (!arguments.length) return url;
        url = _;
        oauth.url(_);
        event.auth();
        connection.flush();
        return connection;
    };

    connection.user = function(_) {
        if (!arguments.length) return user;
        user = _;
        return connection;
    };

    connection.flush = function() {
        _.forEach(inflight, abortRequest);
        loadedTiles = {};
        inflight = {};
        return connection;
    };

    connection.logout = function() {
        oauth.logout();
        event.auth();
        return connection;
    };

    connection.keys = function(_) {
        if (!arguments.length) return keys;
        keys = _;
        oauth.keys(keys);
        return connection;
    };

    connection.authenticate = function(callback) {
        function done(err, res) {
            event.auth();
            if (callback) callback(err, res);
        }
        return oauth.authenticate(done);
    };

    connection.version = function(_) {
        if (!arguments.length) return version;
        version = _;
        return connection;
    };

    connection.bboxFromAPI = bboxFromAPI;
    connection.loadFromURL = loadFromURL;
    connection.loadTiles = _.debounce(loadTiles, 100);
    connection.userDetails = userDetails;
    connection.authenticated = authenticated;
    connection.objectData = objectData;

    return d3.rebind(connection, event, 'on');
};
<commit_msg>Remove vestigial code<commit_after>iD.Connection = function() {

    var event = d3.dispatch('auth', 'load'),
        url = 'http://www.openstreetmap.org',
        connection = {},
        user = {},
        version,
        keys,
        inflight = {},
        loadedTiles = {},
        oauth = iD.OAuth().url(url);

    function bboxUrl(b) {
        return url + '/api/0.6/map?bbox=' + [b[0][0],b[1][1],b[1][0],b[0][1]];
    }

    function bboxFromAPI(box, tile, callback) {
        function done(err, parsed) {
             loadedTiles[tile.toString()] = true;
             delete inflight[tile.toString()];
             callback(err, parsed);
         }
         inflight[tile.toString()] = loadFromURL(bboxUrl(box), done);
    }

    function loadFromURL(url, callback) {
        function done(dom) {
            return callback(null, parse(dom));
        }
        return d3.xml(url).get().on('load', done);
    }

    function getNodes(obj) {
        var nelems = obj.getElementsByTagName('nd'), nodes = new Array(nelems.length);
        for (var i = 0, l = nelems.length; i < l; i++) {
            nodes[i] = 'n' + nelems[i].attributes.ref.nodeValue;
        }
        return nodes;
    }

    function getTags(obj) {
        var tags = {}, tagelems = obj.getElementsByTagName('tag');
        for (var i = 0, l = tagelems.length; i < l; i++) {
            var item = tagelems[i];
            tags[item.attributes.k.nodeValue] = item.attributes.v.nodeValue;
        }
        return tags;
    }

    function getMembers(obj) {
        var elems = obj.getElementsByTagName('member'),
            members = new Array(elems.length);

        for (var i = 0, l = elems.length; i < l; i++) {
            members[i] = {
                id: elems[i].attributes.type.nodeValue[0] + elems[i].attributes.ref.nodeValue,
                type: elems[i].attributes.type.nodeValue,
                role: elems[i].attributes.role.nodeValue
            };
        }
        return members;
    }

    function objectData(obj) {
        switch(obj.type) {
            case 'node': return nodeData(obj);
            case 'way': return wayData(obj);
            case 'relation': return relationData(obj);
        }
    }

    function nodeData(obj) {
        var o = { type: 'node', tags: getTags(obj) };
        for (var i = 0, l = obj.attributes.length; i < l; i++) {
            o[obj.attributes[i].nodeName] = obj.attributes[i].nodeValue;
        }
        if (o.lon && o.lat) {
            o.loc = [parseFloat(o.lon), parseFloat(o.lat)];
            delete o.lon; delete o.lat;
        }
        o.id = iD.Entity.id.fromOSM('node', o.id);
        return new iD.Node(o);
    }

    function wayData(obj) {
        var o = { type: 'way', nodes: getNodes(obj),
            tags: getTags(obj)
        };
        for (var i = 0, l = obj.attributes.length; i < l; i++) {
            o[obj.attributes[i].nodeName] = obj.attributes[i].nodeValue;
        }
        o.id = iD.Entity.id.fromOSM('way', o.id);
        return new iD.Way(o);
    }

    function relationData(obj) {
        var o = {
            type: 'relation', members: getMembers(obj),
            tags: getTags(obj)
        };
        for (var i = 0, l = obj.attributes.length; i < l; i++) {
            o[obj.attributes[i].nodeName] = obj.attributes[i].nodeValue;
        }
        o.id = iD.Entity.id.fromOSM('relation', o.id);
        return new iD.Relation(o);
    }

    function parse(dom) {
        if (!dom || !dom.childNodes) return new Error('Bad request');
        var root = dom.childNodes[0];
        var entities = {};

        var i, o, l;
        for (i = 0, l = root.childNodes.length; i < l; i++) {
            switch(root.childNodes[i].nodeName) {
                case 'node':
                    o = nodeData(root.childNodes[i]);
                    entities[o.id] = o;
                    break;
                case 'way':
                    o = wayData(root.childNodes[i]);
                    entities[o.id] = o;
                    break;
                case 'relation':
                    o = relationData(root.childNodes[i]);
                    entities[o.id] = o;
                    break;
            }
        }

        return iD.Graph(entities);
    }

    function authenticated() {
        return oauth.authenticated();
    }

    // Generate Changeset XML. Returns a string.
    connection.changesetJXON = function(tags) {
        return {
            osm: {
                changeset: {
                    tag: _.map(tags, function(value, key) {
                        return { '@k': key, '@v': value };
                    }),
                    '@version': 0.3,
                    '@generator': 'iD'
                }
            }
        };
    };

    // Generate [osmChange](http://wiki.openstreetmap.org/wiki/OsmChange)
    // XML. Returns a string.
    connection.osmChangeJXON = function(userid, changeset_id, changes) {
        function nest(x, order) {
            var groups = {};
            for (var i = 0; i < x.length; i++) {
                var tagName = Object.keys(x[i])[0];
                if (!groups[tagName]) groups[tagName] = [];
                groups[tagName].push(x[i][tagName]);
            }
            var ordered = {};
            order.forEach(function(o) {
                if (groups[o]) ordered[o] = groups[o];
            });
            return ordered;
        }

        function rep(entity) {
            return entity.asJXON(changeset_id);
        }

        return {
            osmChange: {
                '@version': 0.3,
                '@generator': 'iD',
                'create': nest(changes.created.map(rep), ['node', 'way', 'relation']),
                'modify': nest(changes.modified.map(rep), ['node', 'way', 'relation']),
                'delete': _.extend(nest(changes.deleted.map(rep), ['relation', 'way', 'node']), {'@if-unused': true})
            }
        };
    };

    connection.putChangeset = function(changes, comment, imagery_used, callback) {
        oauth.xhr({
                method: 'PUT',
                path: '/api/0.6/changeset/create',
                options: { header: { 'Content-Type': 'text/xml' } },
                content: JXON.stringify(connection.changesetJXON({
                    imagery_used: imagery_used.join(';'),
                    comment: comment,
                    created_by: 'iD ' + (version || '')
                }))
            }, function (err, changeset_id) {
                if (err) return callback(err);
                oauth.xhr({
                    method: 'POST',
                    path: '/api/0.6/changeset/' + changeset_id + '/upload',
                    options: { header: { 'Content-Type': 'text/xml' } },
                    content: JXON.stringify(connection.osmChangeJXON(user.id, changeset_id, changes))
                }, function (err) {
                    if (err) return callback(err);
                    oauth.xhr({
                        method: 'PUT',
                        path: '/api/0.6/changeset/' + changeset_id + '/close'
                    }, function (err) {
                        callback(err, changeset_id);
                    });
                });
            });
    };

    function userDetails(callback) {
        function done(err, user_details) {
            var u = user_details.getElementsByTagName('user')[0],
                img = u.getElementsByTagName('img'),
                image_url = '';
            if (img && img[0].getAttribute('href')) {
                image_url = img[0].getAttribute('href');
            }
            callback(connection.user({
                display_name: u.attributes.display_name.nodeValue,
                image_url: image_url,
                id: u.attributes.id.nodeValue
            }).user());
        }
        oauth.xhr({ method: 'GET', path: '/api/0.6/user/details' }, done);
    }

    function tileAlreadyLoaded(c) { return !loadedTiles[c.toString()] && !inflight[c.toString()]; }

    function abortRequest(i) { i.abort(); }

    function loadTile(e) {
        function done(err, g) {
            event.load(err, g);
        }
        bboxFromAPI(e.box, e.tile, done);
    }

    function loadTiles(projection, dimensions) {
        var scaleExtent = [16, 16],
            s = projection.scale(),
            tiles = d3.geo.tile()
                .scaleExtent(scaleExtent)
                .scale(s)
                .size(dimensions)
                .translate(projection.translate())(),
            z = Math.max(Math.log(s) / Math.log(2) - 8, 0),
            rz = Math.max(scaleExtent[0], Math.min(scaleExtent[1], Math.floor(z))),
            ts = 256 * Math.pow(2, z - rz),
            tile_origin = [
                s / 2 - projection.translate()[0],
                s / 2 - projection.translate()[1]];

        function apiExtentBox(c) {
            var x = (c[0] * ts) - tile_origin[0];
            var y = (c[1] * ts) - tile_origin[1];
            return {
                box: [
                    projection.invert([x, y]),
                    projection.invert([x + ts, y + ts])],
                tile: c
            };
        }

        _.filter(inflight, function(v, i) {
            var wanted = _.find(tiles, function(tile) {
                return i === tile.toString();
            });
            if (!wanted) delete inflight[i];
            return !wanted;
        }).map(abortRequest);

        tiles
            .filter(tileAlreadyLoaded)
            .map(apiExtentBox)
            .forEach(loadTile);
    }

    connection.userUrl = function(username) {
        return url + "/user/" + username;
    };

    connection.url = function(_) {
        if (!arguments.length) return url;
        url = _;
        oauth.url(_);
        event.auth();
        connection.flush();
        return connection;
    };

    connection.user = function(_) {
        if (!arguments.length) return user;
        user = _;
        return connection;
    };

    connection.flush = function() {
        _.forEach(inflight, abortRequest);
        loadedTiles = {};
        inflight = {};
        return connection;
    };

    connection.logout = function() {
        oauth.logout();
        event.auth();
        return connection;
    };

    connection.keys = function(_) {
        if (!arguments.length) return keys;
        keys = _;
        oauth.keys(keys);
        return connection;
    };

    connection.authenticate = function(callback) {
        function done(err, res) {
            event.auth();
            if (callback) callback(err, res);
        }
        return oauth.authenticate(done);
    };

    connection.version = function(_) {
        if (!arguments.length) return version;
        version = _;
        return connection;
    };

    connection.bboxFromAPI = bboxFromAPI;
    connection.loadFromURL = loadFromURL;
    connection.loadTiles = _.debounce(loadTiles, 100);
    connection.userDetails = userDetails;
    connection.authenticated = authenticated;
    connection.objectData = objectData;

    return d3.rebind(connection, event, 'on');
};
<|endoftext|>


<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 * IO type for scenery Event
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  const Vector2IO = require( 'DOT/Vector2IO' );
  const scenery = require( 'SCENERY/scenery' );

  // ifphetio
  const assertInstanceOf = require( 'ifphetio!PHET_IO/assertInstanceOf' );
  const ObjectIO = require( 'ifphetio!PHET_IO/types/ObjectIO' );
  const phetioInherit = require( 'ifphetio!PHET_IO/phetioInherit' );

  /**
   * IO type for phet/scenery's Event class.
   * @param {Event} event
   * @param phetioID
   * @constructor
   */
  function EventIO( event, phetioID ) {
    assert && assertInstanceOf( event, scenery.Event );
    ObjectIO.call( this, event, phetioID );
  }

  phetioInherit( ObjectIO, 'EventIO', EventIO, {}, {
    get documentation() { return 'An event, with a point'; },

    /**
     * Encodes a Color into a state object.
     * @param {Event} event
     * @returns {Object}
     */
    toStateObject( event ) {
      assert && assertInstanceOf( event, scenery.Event );

      var eventObject = {
        type: event.type,
        domEventType: event.domEvent.type
      };
      if ( event.pointer && event.pointer.point ) {
        eventObject.point = Vector2IO.toStateObject( event.pointer.point );
      }

      // Note: If changing the contents of this object, please document it in the public documentation string.
      return eventObject;
    }
  } );

  return scenery.register( 'EventIO', EventIO );
} );

<commit_msg>Overrides, see https://github.com/phetsims/phet-io/issues/1278<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 * IO type for scenery Event
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  const Vector2IO = require( 'DOT/Vector2IO' );
  const scenery = require( 'SCENERY/scenery' );

  // ifphetio
  const assertInstanceOf = require( 'ifphetio!PHET_IO/assertInstanceOf' );
  const ObjectIO = require( 'ifphetio!PHET_IO/types/ObjectIO' );
  const phetioInherit = require( 'ifphetio!PHET_IO/phetioInherit' );

  /**
   * IO type for phet/scenery's Event class.
   * @param {Event} event
   * @param phetioID
   * @constructor
   */
  function EventIO( event, phetioID ) {
    assert && assertInstanceOf( event, scenery.Event );
    ObjectIO.call( this, event, phetioID );
  }

  phetioInherit( ObjectIO, 'EventIO', EventIO, {}, {
    get documentation() { return 'An event, with a point'; },

    /**
     * Encodes a Color into a state object.
     * @param {Event} event
     * @returns {Object}
     * @override
     */
    toStateObject( event ) {
      assert && assertInstanceOf( event, scenery.Event );

      var eventObject = {
        type: event.type,
        domEventType: event.domEvent.type
      };
      if ( event.pointer && event.pointer.point ) {
        eventObject.point = Vector2IO.toStateObject( event.pointer.point );
      }

      // Note: If changing the contents of this object, please document it in the public documentation string.
      return eventObject;
    }
  } );

  return scenery.register( 'EventIO', EventIO );
} );

<|endoftext|>


<commit_before>/*
 * jQuery Reveal Plugin 1.0
 * www.ZURB.com
 * Copyright 2010, ZURB
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
*/

(function($) {

/*---------------------------
 Defaults for Reveal
----------------------------*/

/*---------------------------
 Listener for data-reveal-id attributes
----------------------------*/

	$('a[data-reveal-id]').live('click', function(e) {
		e.preventDefault();
		var modalLocation = $(this).attr('data-reveal-id');
		$('#'+modalLocation).reveal($(this).data());
	});

/*---------------------------
 Extend and Execute
----------------------------*/

    $.fn.reveal = function(options) {

        var defaults = {
	    	animation: 'fadeAndPop', //fade, fadeAndPop, none
		    animationspeed: 300, //how fast animtions are
		    closeonbackgroundclick: true, //if you click background will modal close?
		    dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal
    	};

        //Extend dem' options
        var options = $.extend({}, defaults, options);

        return this.each(function() {

/*---------------------------
 Global Variables
----------------------------*/
        	var modal = $(this),
        		topMeasure  = parseInt(modal.css('top')),
				topOffset = modal.height() + topMeasure,
          		locked = false,
				modalBG = $('.reveal-modal-bg');

/*---------------------------
 Create Modal BG
----------------------------*/
			if(modalBG.length == 0) {
				modalBG = $('
').insertAfter(modal);
			}

/*---------------------------
 Open & Close Animations
----------------------------*/
			//Entrance Animations
			modal.bind('reveal:open', function () {
			  modalBG.unbind('click.modalEvent');
				$('.' + options.dismissmodalclass).unbind('click.modalEvent');
				if(!locked) {
					lockModal();
					if(options.animation == "fadeAndPop") {
						modal.css({'top': $(document).scrollTop()-topOffset, 'opacity' : 0, 'visibility' : 'visible'});
						modalBG.fadeIn(options.animationspeed/2);
						modal.delay(options.animationspeed/2).animate({
							"top": $(document).scrollTop()+topMeasure + 'px',
							"opacity" : 1
						}, options.animationspeed,unlockModal());
					}
					if(options.animation == "fade") {
						modal.css({'opacity' : 0, 'visibility' : 'visible', 'top': $(document).scrollTop()+topMeasure});
						modalBG.fadeIn(options.animationspeed/2);
						modal.delay(options.animationspeed/2).animate({
							"opacity" : 1
						}, options.animationspeed,unlockModal());
					}
					if(options.animation == "none") {
						modal.css({'visibility' : 'visible', 'top':$(document).scrollTop()+topMeasure});
						modalBG.css({"display":"block"});
						unlockModal()
					}
				}
				modal.unbind('reveal:open');
			});

			//Closing Animation
			modal.bind('reveal:close', function () {
			  if(!locked) {
					lockModal();
					if(options.animation == "fadeAndPop") {
						modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
						modal.animate({
							"top":  $(document).scrollTop()-topOffset + 'px',
							"opacity" : 0
						}, options.animationspeed/2, function() {
							modal.css({'top':topMeasure, 'opacity' : 1, 'visibility' : 'hidden'});
							unlockModal();
						});
					}
					if(options.animation == "fade") {
						modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
						modal.animate({
							"opacity" : 0
						}, options.animationspeed, function() {
							modal.css({'opacity' : 1, 'visibility' : 'hidden', 'top' : topMeasure});
							unlockModal();
						});
					}
					if(options.animation == "none") {
						modal.css({'visibility' : 'hidden', 'top' : topMeasure});
						modalBG.css({'display' : 'none'});
					}
				}
				modal.unbind('reveal:close');
			});

/*---------------------------
 Open and add Closing Listeners
----------------------------*/
        	//Open Modal Immediately
    	modal.trigger('reveal:open')

			//Close Modal Listeners
			var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function () {
			  modal.trigger('reveal:close')
			});

			if(options.closeonbackgroundclick) {
				modalBG.css({"cursor":"pointer"})
				modalBG.bind('click.modalEvent', function () {
				  modal.trigger('reveal:close')
				});
			}
			$('body').keyup(function(e) {
        		if(e.which===27){ modal.trigger('reveal:close'); } // 27 is the keycode for the Escape key
			});

/*---------------------------
 Animations Locks
----------------------------*/
			function unlockModal() {
				locked = false;
			}
			function lockModal() {
				locked = true;
			}

        });//each call
    }//orbit plugin call
})(jQuery);

<commit_msg>update reveal.js for ie opacity on modal bg<commit_after>/*
 * jQuery Reveal Plugin 1.0
 * www.ZURB.com
 * Copyright 2010, ZURB
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
*/

(function($) {

/*---------------------------
 Defaults for Reveal
----------------------------*/

/*---------------------------
 Listener for data-reveal-id attributes
----------------------------*/

	$('a[data-reveal-id]').live('click', function(e) {
		e.preventDefault();
		var modalLocation = $(this).attr('data-reveal-id');
		$('#'+modalLocation).reveal($(this).data());
	});

/*---------------------------
 Extend and Execute
----------------------------*/

    $.fn.reveal = function(options) {

        var defaults = {
	    	animation: 'fadeAndPop', //fade, fadeAndPop, none
		    animationspeed: 300, //how fast animtions are
		    closeonbackgroundclick: true, //if you click background will modal close?
		    dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal
    	};

        //Extend dem' options
        var options = $.extend({}, defaults, options);

        return this.each(function() {

/*---------------------------
 Global Variables
----------------------------*/
        	var modal = $(this),
        		topMeasure  = parseInt(modal.css('top')),
				topOffset = modal.height() + topMeasure,
          		locked = false,
				modalBG = $('.reveal-modal-bg');

/*---------------------------
 Create Modal BG
----------------------------*/
			if(modalBG.length == 0) {
				modalBG = $('
').insertAfter(modal).css('filter', 'alpha(opacity=80)');
			}

/*---------------------------
 Open & Close Animations
----------------------------*/
			//Entrance Animations
			modal.bind('reveal:open', function () {
			  modalBG.unbind('click.modalEvent');
				$('.' + options.dismissmodalclass).unbind('click.modalEvent');
				if(!locked) {
					lockModal();
					if(options.animation == "fadeAndPop") {
						modal.css({'top': $(document).scrollTop()-topOffset, 'opacity' : 0, 'visibility' : 'visible'});
						modalBG.fadeIn(options.animationspeed/2);
						modal.delay(options.animationspeed/2).animate({
							"top": $(document).scrollTop()+topMeasure + 'px',
							"opacity" : 1
						}, options.animationspeed,unlockModal());
					}
					if(options.animation == "fade") {
						modal.css({'opacity' : 0, 'visibility' : 'visible', 'top': $(document).scrollTop()+topMeasure});
						modalBG.fadeIn(options.animationspeed/2);
						modal.delay(options.animationspeed/2).animate({
							"opacity" : 1
						}, options.animationspeed,unlockModal());
					}
					if(options.animation == "none") {
						modal.css({'visibility' : 'visible', 'top':$(document).scrollTop()+topMeasure});
						modalBG.css({"display":"block"});
						unlockModal()
					}
				}
				modal.unbind('reveal:open');
			});

			//Closing Animation
			modal.bind('reveal:close', function () {
			  if(!locked) {
					lockModal();
					if(options.animation == "fadeAndPop") {
						modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
						modal.animate({
							"top":  $(document).scrollTop()-topOffset + 'px',
							"opacity" : 0
						}, options.animationspeed/2, function() {
							modal.css({'top':topMeasure, 'opacity' : 1, 'visibility' : 'hidden'});
							unlockModal();
						});
					}
					if(options.animation == "fade") {
						modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
						modal.animate({
							"opacity" : 0
						}, options.animationspeed, function() {
							modal.css({'opacity' : 1, 'visibility' : 'hidden', 'top' : topMeasure});
							unlockModal();
						});
					}
					if(options.animation == "none") {
						modal.css({'visibility' : 'hidden', 'top' : topMeasure});
						modalBG.css({'display' : 'none'});
					}
				}
				modal.unbind('reveal:close');
			});

/*---------------------------
 Open and add Closing Listeners
----------------------------*/
        	//Open Modal Immediately
    	modal.trigger('reveal:open')

			//Close Modal Listeners
			var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function () {
			  modal.trigger('reveal:close')
			});

			if(options.closeonbackgroundclick) {
				modalBG.css({"cursor":"pointer"})
				modalBG.bind('click.modalEvent', function () {
				  modal.trigger('reveal:close')
				});
			}
			$('body').keyup(function(e) {
        		if(e.which===27){ modal.trigger('reveal:close'); } // 27 is the keycode for the Escape key
			});

/*---------------------------
 Animations Locks
----------------------------*/
			function unlockModal() {
				locked = false;
			}
			function lockModal() {
				locked = true;
			}

        });//each call
    }//orbit plugin call
})(jQuery);

<|endoftext|>


<commit_before>/*
 * Generates a lightweight Network graph, using cytoscapeJS, jQuery and jQuery UI.
 * @author: Ajit Singh.
 */
window.onload= function() {
 launchNetwork($('#dataset_dropdown').val());
}

function launchNetwork(jsonFileName) {
    var jsonFile= jsonFileName; // the JSON file selected by the user.
	//console.log("generateCyJSNetwork>> input dataset: "+ jsonFile);
    try {
        // Show maskloader.
        showNetworkLoader();

        // Generate the Network Graph after the page load event.
        generateNetworkGraph(jsonFile);

        // Remove maskloader.
        removeNetworkLoader();
       }
    catch(err) {
          var errorMsg= err.stack;
          console.log("Error:
"+"Details: "+ errorMsg);
         }
}
<commit_msg>moved knet-menu to launchNetwork.js<commit_after>/*
 * Generates a lightweight Network graph, using cytoscapeJS, jQuery and jQuery UI.
 * @author: Ajit Singh.
 */
window.onload= function() {
 // Add KnetMaps menu bar
 var knet_menu= "<input type='image' id='maximizeOverlay' src='image/maximizeOverlay.png' title='Toggle full screen' onclick='OnMaximizeClick();' onmouseover='onHover($(this));' onmouseout='offHover($(this));'>"+
                    "<input type='image' id='showAll' src='image/showAll.png' onclick='showAll();' title='Show all the concept & relations in the Network' onmouseover='onHover($(this));' onmouseout='offHover($(this));'>"+
                    "<input type='image' id='relayoutNetwork' src='image/relayoutNetwork.png' onclick='rerunLayout();' title='Re-run the Layout' onmouseover='onHover($(this));' onmouseout='offHover($(this));'>"+
                    ""+
                        "<select id='layouts_dropdown' class='knet-dropdowns' onChange='rerunLayout();' title='Select network layout'>"+
                            "<option value='Cose_layout' selected='selected' title='using CoSE layout algorithm (useful for larger networks with clustering)'>CoSE layout</option>"+
                            "<option value='ngraph_force_layout' title='using ngraph_force layout (works well on planar graphs)'>Force layout</option>"+
                            "<option value='Circle_layout'>Circular layout</option>"+
                            "<option value='Concentric_layout'>Concentric layout</option>"+
                            "<option value='Cose_Bilkent_layout' title='using CoSE-Bilkent layout (with node clustering, but performance-intensive for larger networks)'>CoSE-Bilkent layout</option>"+
                        "</select>"+
                        "<select id='changeLabelVisibility' class='knet-dropdowns' onChange='showHideLabels(this.value);' title='Select label visibility'>"+
                            "<option value='None' selected='selected'>Labels: None</option>"+
                            "<option value='Concepts'>Labels: Concepts</option>"+
                            "<option value='Relations'>Labels: Relations</option>"+
                            "<option value='Both'>Labels: Both</option>"+
                        "</select>"+
                        "<select id='changeLabelFont' class='knet-dropdowns' onChange='changeLabelFontSize(this.value);' title='Select label font size'>"+
                            "<option value='8'>Label size: 8px</option>"+
                            "<option value='12'>Label size: 12px</option>"+
                            "<option value='16' selected='selected'>Label size: 16px</option>"+
                            "<option value='20'>Label size: 20px</option>"+
                            "<option value='24'>Label size: 24px</option>"+
                            "<option value='28'>Label size: 28px</option>"+
                            "<option value='32'>Label size: 32px</option>"+
                            "<option value='36'>Label size: 36px</option>"+
                            "<option value='40'>Label size: 40px</option>"+
                        "</select>"+
			        ""+
                    "<input type='image' id='resetNetwork' src='image/resetNetwork.png' onclick='resetGraph();' title='Reposition (reset and re-fit) the graph' onmouseover='onHover($(this));' onmouseout='offHover($(this));'>"+
                    "<input type='image' id='savePNG' src='image/savePNG.png' onclick='exportAsImage();' title='Export the network as a .png image' onmouseover='onHover($(this));' onmouseout='offHover($(this));'>"+
                    "<input type='image' id='saveJSON' src='image/saveJSON.png' onclick='exportAsJson();' title='Export the network in JSON format' onmouseover='onHover($(this));' onmouseout='offHover($(this));'>"+
                    "<input type='image' id='helpURL' src='image/help.png' onclick='openKnetHelpPage();' title='Go to help documentation' onmouseover='onHover($(this));' onmouseout='offHover($(this));'>";
 $('#knetmaps-menu').html(knet_menu);

 launchNetwork($('#dataset_dropdown').val());
}

function launchNetwork(jsonFileName) {
    var jsonFile= jsonFileName; // the JSON file selected by the user.
	//console.log("generateCyJSNetwork>> input dataset: "+ jsonFile);
    try {
        // Show maskloader.
        showNetworkLoader();

        // Generate the Network Graph after the page load event.
        generateNetworkGraph(jsonFile);

        // Remove maskloader.
        removeNetworkLoader();
       }
    catch(err) {
          var errorMsg= err.stack;
          console.log("Error:
"+"Details: "+ errorMsg);
         }
}
<|endoftext|>


<commit_before>/**
 * Initialize Loggly sensor
 */
window.Log = new loggly({
    url: (("https:" == document.location.protocol)
            ? "https://logs.loggly.com"
            : "http://logs.loggly.com")
            + '/inputs/eea8d878-db25-43f4-b3b8-18053bb54004?rt=1',
    level: 'log'
});

/**
 * Log errors to Loggly
 */
window.defaultHandler = window.error;
window.onerror = function(errorMsg, url, lineNumber) {
    if (lineNumber !== 0) {
        Log.log("\n" +
        		"Browser: " + Log.user_agent + "\n" +
        		"Message: " + errorMsg + "\n" +
        		"File: " + url + "\n" +
        	    "Line no: " + lineNumber
        );
    }

    if (defaultHandler) {
        return defaultHandler(errorMsg, url, lineNumber);
    }

    return true;
};<commit_msg>Log raw user agent<commit_after>/**
 * Initialize Loggly sensor
 */
window.Log = new loggly({
    url: (("https:" == document.location.protocol)
            ? "https://logs.loggly.com"
            : "http://logs.loggly.com")
            + '/inputs/eea8d878-db25-43f4-b3b8-18053bb54004?rt=1',
    level: 'log'
});

/**
 * Log errors to Loggly
 */
window.defaultHandler = window.error;
window.onerror = function(errorMsg, url, lineNumber) {
    if (lineNumber !== 0) {
        Log.log("\n" +
        		"Browser: " + navigator.userAgent + "\n" +
        		"Message: " + errorMsg + "\n" +
        		"File: " + url + "\n" +
        	    "Line no: " + lineNumber
        );
    }

    if (defaultHandler) {
        return defaultHandler(errorMsg, url, lineNumber);
    }

    return true;
};<|endoftext|>


<commit_before>// -------------------------------------------------
// -------------------- Master ---------------------
// -------------------------------------------------

function DebugMessage(message) {
    console.log(message);
}

// small uart device
function UARTDev(worker) {
    this.ReceiveChar = function(c) {
            worker.SendToWorker("tty0", c);
    };
}

function jor1kGUI(termid, fbid, statsid, imageurls, relayURL)
{
    this.urls = imageurls;

    this.worker = new Worker('js/worker/worker.js');
    this.worker.onmessage = this.OnMessage.bind(this);
    this.worker.onerror = function(e) {
        console.log("Error at " + e.filename + ":" + e.lineno + ": " + e.message);
    }

    this.SendToWorker = function(command, data) {
        this.worker.postMessage(
        {
            "command": command,
            "data": data
        });
    }

    this.ChangeCore = function(core) {
        this.SendToWorker("ChangeCore", core);
    };

    this.ChangeImage = function(newurl) {
        this.urls[1] = newurl;
        this.Reset();
    };
    this.Reset= function () {
      this.stop = false; // VM Stopped/Aborted
      this.userpaused = false;
      this.executepending=false; // if we rec an execute message while paused
      this.SendToWorker("Reset");
      this.SendToWorker("LoadAndStart", this.urls);
      this.term.PauseBlink(false);
    }
    this.Pause = function(pause) {
      pause = !! pause; // coerce to boolean
      if(pause == this.userpaused) return;
      this.userpaused = pause;
      if(! this.userpaused && this.executepending) {
        this.executepending = false;
         this.SendToWorker("execute", 0);
      }
      this.term.PauseBlink(pause);
    }

    this.terminalcanvas = document.getElementById(termid);
    this.stats = document.getElementById(statsid);

    this.term = new Terminal(24, 80, termid);
    this.terminput = new TerminalInput(new UARTDev(this));

    this.IgnoreKeys = function() {
      //Simpler but not as general, return( document.activeElement.type==="textarea" || document.activeElement.type==='input');
      return (this.lastMouseDownTarget != this.terminalcanvas);
    }
    var recordTarget = function(event) {
            this.lastMouseDownTarget = event.target;
        }.bind(this);

    if(document.addEventListener)
      document.addEventListener('mousedown', recordTarget, false);
    else
      Window.onmousedown = recordTarget; // IE 10 support (untested)

    document.onkeypress = function(event) {
        if(this.IgnoreKeys()) return true;
        this.SendToWorker("keypress", {keyCode:event.keyCode, charCode:event.charCode});
        return this.terminput.OnKeyPress(event);
    }.bind(this);

    document.onkeydown = function(event) {
        if(this.IgnoreKeys()) return true;
        this.SendToWorker("keydown", {keyCode:event.keyCode, charCode:event.charCode});
        return this.terminput.OnKeyDown(event);
    }.bind(this);

    document.onkeyup = function(event) {
        if(this.IgnoreKeys()) return true;
        this.SendToWorker("keyup", {keyCode:event.keyCode, charCode:event.charCode});
        return this.terminput.OnKeyUp(event);
    }.bind(this);

    this.ethernet = new Ethernet(relayURL);
    this.ethernet.onmessage = function(e) {
        this.SendToWorker("ethmac", e.data);
    }.bind(this);

    this.InitFramebuffer(fbid);

    this.Reset();

    window.setInterval(function(){this.SendToWorker("GetIPS", 0)}.bind(this), 1000);
}

jor1kGUI.prototype.OnMessage = function(e) {
    if (this.stop) return;
    switch(e.data.command)
    {
        case "execute":  // this command is send back and forth to be responsive
            if(this.userpaused) {
              this.executepending = true;
            } else {
              this.executepending = false;
              this.SendToWorker("execute", 0);
            }
            break;
        case "ethmac":
            this.ethernet.SendFrame(e.data.data);
            break;
        case "tty0":
            this.term.PutChar(e.data.data);
            break;
        case "GetFB":
            this.UpdateFramebuffer(e.data.data);
            break;
        case "Stop":
            console.log("Received stop signal");
            this.stop = true;
            break;
        case "GetIPS":
            this.stats.innerHTML = this.userpaused ? "Paused" : (Math.floor(e.data.data/100000)/10.) + " MIPS";
            break;
        case "Debug":
            console.log(e.data.data);
            break;
    }
}

// Init Framebuffer if it exists
jor1kGUI.prototype.InitFramebuffer = function(fbid) {
    this.fbcanvas = document.getElementById(fbid);
    if(!this.fbcanvas) return;

    this.fbctx = this.fbcanvas.getContext("2d");
    this.fbimageData = this.fbctx.createImageData(this.fbcanvas.width, this.fbcanvas.height);

    this.terminalcanvas.onmousedown = function(event) {
        this.fbcanvas.style.border = "2px solid #000000";
    }.bind(this);

    this.fbcanvas.onmousedown = function(event) {
        this.fbcanvas.style.border = "2px solid #FF0000";
        var rect = this.fbcanvas.getBoundingClientRect();
        var x = event.clientX - rect.left;
        var y = event.clientY - rect.top;
        this.SendToWorker("tsmousedown", {x:x, y:y});
    }.bind(this);

    this.fbcanvas.onmouseup = function(event) {
        var rect = this.fbcanvas.getBoundingClientRect();
        var x = event.clientX - rect.left;
        var y = event.clientY - rect.top;
        this.SendToWorker("tsmouseup", {x:x, y:y});
    }.bind(this);

    this.fbcanvas.onmousemove = function(event) {
        var rect = this.fbcanvas.getBoundingClientRect();
        var x = event.clientX - rect.left;
        var y = event.clientY - rect.top;
        this.SendToWorker("tsmousemove", {x:x, y:y});
    }.bind(this);

    // receive the contents of the framebuffer every 100ms
    window.setInterval(function(){this.SendToWorker("GetFB", 0)}.bind(this), 100);
}

jor1kGUI.prototype.UpdateFramebuffer = function(buffer) {
    if(this.userpaused) return;
    var i=0, n = buffer.length;
    var data = this.fbimageData.data;

    for (i = 0; i < n; ++i) {
        var x = buffer[i];
        data[(i<<2)+0] = (x>>16)&0xFF;
        data[(i<<2)+1] = (x>>8)&0xFF;
        data[(i<<2)+2] = (x)&0xFF;
        data[(i<<2)+3] = 0xFF;
    }

    //data.set(buffer);
    this.fbctx.putImageData(this.fbimageData, 0, 0); // at coords 0,0
}

<commit_msg>Hotfix for framebuffer keyboard handling<commit_after>// -------------------------------------------------
// -------------------- Master ---------------------
// -------------------------------------------------

function DebugMessage(message) {
    console.log(message);
}

// small uart device
function UARTDev(worker) {
    this.ReceiveChar = function(c) {
        if (worker.lastMouseDownTarget != worker.fbcanvas) {
            worker.SendToWorker("tty0", c);
        }
    };
}

function jor1kGUI(termid, fbid, statsid, imageurls, relayURL)
{
    this.urls = imageurls;

    this.worker = new Worker('js/worker/worker.js');
    this.worker.onmessage = this.OnMessage.bind(this);
    this.worker.onerror = function(e) {
        console.log("Error at " + e.filename + ":" + e.lineno + ": " + e.message);
    }

    this.SendToWorker = function(command, data) {
        this.worker.postMessage(
        {
            "command": command,
            "data": data
        });
    }

    this.ChangeCore = function(core) {
        this.SendToWorker("ChangeCore", core);
    };

    this.ChangeImage = function(newurl) {
        this.urls[1] = newurl;
        this.Reset();
    };
    this.Reset= function () {
      this.stop = false; // VM Stopped/Aborted
      this.userpaused = false;
      this.executepending=false; // if we rec an execute message while paused
      this.SendToWorker("Reset");
      this.SendToWorker("LoadAndStart", this.urls);
      this.term.PauseBlink(false);
    }
    this.Pause = function(pause) {
      pause = !! pause; // coerce to boolean
      if(pause == this.userpaused) return;
      this.userpaused = pause;
      if(! this.userpaused && this.executepending) {
        this.executepending = false;
         this.SendToWorker("execute", 0);
      }
      this.term.PauseBlink(pause);
    }

    this.terminalcanvas = document.getElementById(termid);
    this.stats = document.getElementById(statsid);

    this.term = new Terminal(24, 80, termid);
    this.terminput = new TerminalInput(new UARTDev(this));

    this.IgnoreKeys = function() {
      //Simpler but not as general, return( document.activeElement.type==="textarea" || document.activeElement.type==='input');
      return ((this.lastMouseDownTarget != this.terminalcanvas) && (this.lastMouseDownTarget != this.fbcanvas));
    }
    var recordTarget = function(event) {
            this.lastMouseDownTarget = event.target;
        }.bind(this);

    if(document.addEventListener)
      document.addEventListener('mousedown', recordTarget, false);
    else
      Window.onmousedown = recordTarget; // IE 10 support (untested)

    document.onkeypress = function(event) {
        if(this.IgnoreKeys()) return true;
        this.SendToWorker("keypress", {keyCode:event.keyCode, charCode:event.charCode});
        return this.terminput.OnKeyPress(event);
    }.bind(this);

    document.onkeydown = function(event) {
        if(this.IgnoreKeys()) return true;
        this.SendToWorker("keydown", {keyCode:event.keyCode, charCode:event.charCode});
        return this.terminput.OnKeyDown(event);
    }.bind(this);

    document.onkeyup = function(event) {
        if(this.IgnoreKeys()) return true;
        this.SendToWorker("keyup", {keyCode:event.keyCode, charCode:event.charCode});
        return this.terminput.OnKeyUp(event);
    }.bind(this);

    this.ethernet = new Ethernet(relayURL);
    this.ethernet.onmessage = function(e) {
        this.SendToWorker("ethmac", e.data);
    }.bind(this);

    this.InitFramebuffer(fbid);

    this.Reset();

    window.setInterval(function(){this.SendToWorker("GetIPS", 0)}.bind(this), 1000);
}

jor1kGUI.prototype.OnMessage = function(e) {
    if (this.stop) return;
    switch(e.data.command)
    {
        case "execute":  // this command is send back and forth to be responsive
            if(this.userpaused) {
              this.executepending = true;
            } else {
              this.executepending = false;
              this.SendToWorker("execute", 0);
            }
            break;
        case "ethmac":
            this.ethernet.SendFrame(e.data.data);
            break;
        case "tty0":
            this.term.PutChar(e.data.data);
            break;
        case "GetFB":
            this.UpdateFramebuffer(e.data.data);
            break;
        case "Stop":
            console.log("Received stop signal");
            this.stop = true;
            break;
        case "GetIPS":
            this.stats.innerHTML = this.userpaused ? "Paused" : (Math.floor(e.data.data/100000)/10.) + " MIPS";
            break;
        case "Debug":
            console.log(e.data.data);
            break;
    }
}

// Init Framebuffer if it exists
jor1kGUI.prototype.InitFramebuffer = function(fbid) {
    this.fbcanvas = document.getElementById(fbid);
    if(!this.fbcanvas) return;

    this.fbctx = this.fbcanvas.getContext("2d");
    this.fbimageData = this.fbctx.createImageData(this.fbcanvas.width, this.fbcanvas.height);

    this.terminalcanvas.onmousedown = function(event) {
        this.fbcanvas.style.border = "2px solid #000000";
    }.bind(this);

    this.fbcanvas.onmousedown = function(event) {
        this.fbcanvas.style.border = "2px solid #FF0000";
        var rect = this.fbcanvas.getBoundingClientRect();
        var x = event.clientX - rect.left;
        var y = event.clientY - rect.top;
        this.SendToWorker("tsmousedown", {x:x, y:y});
    }.bind(this);

    this.fbcanvas.onmouseup = function(event) {
        var rect = this.fbcanvas.getBoundingClientRect();
        var x = event.clientX - rect.left;
        var y = event.clientY - rect.top;
        this.SendToWorker("tsmouseup", {x:x, y:y});
    }.bind(this);

    this.fbcanvas.onmousemove = function(event) {
        var rect = this.fbcanvas.getBoundingClientRect();
        var x = event.clientX - rect.left;
        var y = event.clientY - rect.top;
        this.SendToWorker("tsmousemove", {x:x, y:y});
    }.bind(this);

    // receive the contents of the framebuffer every 100ms
    window.setInterval(function(){this.SendToWorker("GetFB", 0)}.bind(this), 100);
}

jor1kGUI.prototype.UpdateFramebuffer = function(buffer) {
    if(this.userpaused) return;
    var i=0, n = buffer.length;
    var data = this.fbimageData.data;

    for (i = 0; i < n; ++i) {
        var x = buffer[i];
        data[(i<<2)+0] = (x>>16)&0xFF;
        data[(i<<2)+1] = (x>>8)&0xFF;
        data[(i<<2)+2] = (x)&0xFF;
        data[(i<<2)+3] = 0xFF;
    }

    //data.set(buffer);
    this.fbctx.putImageData(this.fbimageData, 0, 0); // at coords 0,0
}

<|endoftext|>


<commit_before>class MazeGenerator {
  constructor(maxLeafSize, maxWidth, maxHeight) {
    this.maxLeafSize = maxLeafSize;
    this.maxWidth = maxHeight;
    this.left = null;
    this.right = null;
    this.random = new Random(42);
  }

  split() {
    for (var i = 10; i >= 0; i--) {
      console.log(this.random.nextInt());
    }
  }
}<commit_msg>update maze<commit_after>const ROOM_MIN_SIZE = 3;

class MazeGenerator {
  constructor(x, y, width, height) {
    this.random = new Random(42);
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.rooms = [];
    this.walkable = [];
    this.breakable = [];
    this.walls = [];
  }

  split() {
    const split = false;

    do {
      var splitH = true;

      if (width * 1.25 > height) {
        splitH = false;
      } else if (height * 1.25 > width) {
        splitH = true;
      } else if (this.random.nextRange(0, 2)) {
        splitH = false;
      }

      if (splitH) {
        const middle = this.random.nextRange(this.y + MIN_SIZE, this.height - MIN_SIZE);
      } else {
        const middle = this.random.nextRange(this.x + MIN_SIZE, this.width - MIN_SIZE);
      }
    } while (split);
  }
}

// 1,1 => 13,18
<|endoftext|>