<commit_before>const Scroll = (() => {
    let $main_container;

    const sidebarScroll = ($container) => {
        $main_container = $container;

        $container.on('click', '#sidebar-nav li', function () {
            const clicked_li = $(this);
            $.scrollTo($(`.section:eq(${clicked_li.index()})`), 500);
            return false;
        });

        if ($container.length) {
            // grab the initial top offset of the navigation
            const $sidebar                   = $container.find('.sidebar');
            const $sidebar_container         = $container.find('.sidebar-container');
            let width                        = $sidebar.width();
            let sticky_navigation_offset_top = $sidebar.offset().top;

            // With thanks:
            // http://www.backslash.gr/content/blog/webdevelopment/6-navigation-menu-that-stays-on-top-with-jquery

            // our function that decides weather the navigation bar should have "fixed" css position or not.
            const sticky_navigation = () => {
                if (!$sidebar.is(':visible')) return;
                if (!width) {
                    width                        = $sidebar.width();
                    sticky_navigation_offset_top = $sidebar.offset().top;
                }
                const scroll_top = $(window).scrollTop(); // our current vertical position from the top

                // if we've scrolled more than the navigation, change its position to fixed to stick to top,
                // otherwise change it back to relative
                if (scroll_top + $sidebar[0].offsetHeight >
                    $sidebar_container[0].offsetHeight + $sidebar_container.offset().top) {
                    $sidebar.css({ position: 'absolute', bottom: 0, top: '', 'max-width': width, 'width': '100%' });
                } else if (scroll_top > sticky_navigation_offset_top) {
                    $sidebar.css({ position: 'sticky', top: 0, bottom: '', 'max-width': width, 'width': '100%' });
                } else {
                    $sidebar.css({ position: 'relative' });
                }
            };

            // run our function on load
            sticky_navigation();

            const sidebar_nav = $sidebar.find('#sidebar-nav');
            const length      = $container.find('.section').length;
            $(window).on('scroll', function () {
                if (!sidebar_nav.is(':visible')) return;
                // and run it again every time you scroll
                sticky_navigation();

                for (let i = 0; i < length; i++) {
                    const section        = $(`.section:eq(${i})`);
                    const section_offset = section.offset();
                    const is_offset_top  = section_offset && $(this).scrollTop() >= section_offset.top - 5;
                    if (($(window).scrollTop() === 0 || is_offset_top) && section.css('display') !== 'none') { // ignore hidden elements
                        sidebar_nav.find('li').removeClass('selected');

                        if ($(window).scrollTop() === 0 || sidebar_nav.width() === 0) {
                            // We're at the top of the screen, so highlight first nav item
                            sidebar_nav.find('li:first-child').addClass('selected');
                        } else if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
                            // We're at bottom of screen so highlight last nav item.
                            sidebar_nav.find('li:last-child').addClass('selected');
                        } else {
                            sidebar_nav.find(`li:eq(${i})`).addClass('selected');
                        }
                    }
                }
            });
        }
    };

    const scrollToTop = () => {
        let is_displaying = false;
        const $scrollup   = $('#scrollup');
        $(document).scroll(function () {
            if ($(this).scrollTop() > 100) {
                if (is_displaying) return;
                $scrollup.fadeIn();
                is_displaying = true;
            } else if (is_displaying) {
                $scrollup.fadeOut();
                is_displaying = false;
            }
        });

        $scrollup.click(() => {
            $.scrollTo(0, 500);
        });
    };

    return {
        sidebarScroll,
        scrollToTop,
        offScroll: () => {
            $(window).off('scroll');
            if ($main_container) {
                $main_container.find('#sidebar-nav li').off('click');
                $main_container = '';
            }
        },
        goToHashSection: () => {
            $('a[href^="#"]').click(function() {
                $.scrollTo($(`a[name="${$(this).attr('href').substr(1)}"]`), 500, { offset: -10 });
                return false;
            });
            const hash = window.location.hash;
            if (hash) $(`a[href="${hash}"]`).click();
        },
        scrollToHashSection: () => {
            const hash = window.location.hash;
            if (hash) $.scrollTo($(hash));
        },
    };
})();

module.exports = Scroll;
<commit_msg>mahdiyeh/fix: highlight_in_menu_options (#6492)<commit_after>const Scroll = (() => {
    let $main_container,$window_location;

    const sidebarScroll = ($container) => {
        $main_container = $container;
        $window_location = window.location.pathname;

        $container.on('click', '#sidebar-nav li', function () {
            const clicked_li = $(this);
            $.scrollTo($(`.section:eq(${clicked_li.index()})`), 500);
            return false;
        });

        if ($container.length) {
            // grab the initial top offset of the navigation
            const $sidebar                   = $container.find('.sidebar');
            const $sidebar_container         = $container.find('.sidebar-container');
            let width                        = $sidebar.width();
            let sticky_navigation_offset_top = $sidebar.offset().top;

            // With thanks:
            // http://www.backslash.gr/content/blog/webdevelopment/6-navigation-menu-that-stays-on-top-with-jquery

            // our function that decides weather the navigation bar should have "fixed" css position or not.
            const sticky_navigation = () => {
                if (!$sidebar.is(':visible')) return;
                if (!width) {
                    width                        = $sidebar.width();
                    sticky_navigation_offset_top = $sidebar.offset().top;
                }
                const scroll_top = $(window).scrollTop(); // our current vertical position from the top

                // if we've scrolled more than the navigation, change its position to fixed to stick to top,
                // otherwise change it back to relative
                if (scroll_top + $sidebar[0].offsetHeight >
                    $sidebar_container[0].offsetHeight + $sidebar_container.offset().top) {
                    $sidebar.css({ position: 'absolute', bottom: 0, top: '', 'max-width': width, 'width': '100%' });
                } else if (scroll_top > sticky_navigation_offset_top) {
                    $sidebar.css({ position: 'sticky', top: 0, bottom: '', 'max-width': width, 'width': '100%' });
                } else {
                    $sidebar.css({ position: 'relative' });
                }
            };

            // run our function on load
            sticky_navigation();

            const sidebar_nav = $sidebar.find('#sidebar-nav');
            const length      = $container.find('.section').length;
            $(window).on('scroll', function () {
                if (!sidebar_nav.is(':visible')) return;
                // and run it again every time you scroll
                sticky_navigation();

                for (let i = 0; i < length; i++) {
                    const section        = $(`.section:eq(${i})`);
                    const section_offset = section.offset();
                    const is_offset_top  = section_offset && $(this).scrollTop() >= section_offset.top - 5;
                    if (($(window).scrollTop() === 0 || is_offset_top) && section.css('display') !== 'none') { // ignore hidden elements
                        sidebar_nav.find('li').removeClass('selected');

                        if ($(window).scrollTop() === 0 || sidebar_nav.width() === 0) {
                            // We're at the top of the screen, so highlight first nav item
                            sidebar_nav.find('li:first-child').addClass('selected');
                        } else if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
                            // We're at bottom of screen so highlight last nav item.
                            sidebar_nav.find('li:last-child').addClass('selected');
                        } else {
                            sidebar_nav.find(`li:eq(${i})`).addClass('selected');
                        }
                    }
                }
            });
        }
    };

    const scrollToTop = () => {
        let is_displaying = false;
        const $scrollup   = $('#scrollup');
        $(document).scroll(function () {
            if ($(this).scrollTop() > 100) {
                if (is_displaying) return;
                $scrollup.fadeIn();
                is_displaying = true;
            } else if (is_displaying) {
                $scrollup.fadeOut();
                is_displaying = false;
            }
        });

        $scrollup.click(() => {
            $.scrollTo(0, 500);
        });
    };

    return {
        sidebarScroll,
        scrollToTop,
        offScroll: () => {
            if (window.location.pathname !== $window_location) {
                $(window).off('scroll');
            }

            if ($main_container) {
                $main_container.find('#sidebar-nav li').off('click');
                $main_container = '';
            }
        },
        goToHashSection: () => {
            $('a[href^="#"]').click(function() {
                $.scrollTo($(`a[name="${$(this).attr('href').substr(1)}"]`), 500, { offset: -10 });
                return false;
            });
            const hash = window.location.hash;
            if (hash) $(`a[href="${hash}"]`).click();
        },
        scrollToHashSection: () => {
            const hash = window.location.hash;
            if (hash) $.scrollTo($(hash));
        },
    };
})();

module.exports = Scroll;
<|endoftext|>


<commit_before>/**
 * plupload.gears.js
 *
 * Copyright 2009, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

// JSLint defined globals
/*global plupload:false, google:false, window:false */

(function(plupload) {
	var blobs = {};

	function scaleImage(image_blob, width, height, quality, mime) {
		var percentage, canvas, context, scale;

		// Setup canvas and scale
		canvas = google.gears.factory.create('beta.canvas');
		try {
			canvas.decode(image_blob);
			scale = Math.min(width / canvas.width, height / canvas.height);

			if (scale < 1) {
				canvas.resize(Math.round(canvas.width * scale), Math.round(canvas.height * scale));

				return canvas.encode(mime, {quality : quality / 100});
			}
		} catch (e) {
			// Ignore for example when a user uploads a file that can't be decoded
		}

		return image_blob;
	}

	/**
	 * Gears implementation. This runtime supports these features: dragdrop, jpgresize, pngresize, chunks.
	 *
	 * @static
	 * @class plupload.runtimes.Gears
	 * @extends plupload.Runtime
	 */
	plupload.runtimes.Gears = plupload.addRuntime("gears", {
		/**
		 * Returns a list of supported features for the runtime.
		 *
		 * @return {Object} Name/value object with supported features.
		 */
		getFeatures : function() {
			return {
				dragdrop: true,
				jpgresize: true,
				pngresize: true,
				chunks: true,
				progress: true,
				multipart: true
			};
		},

		/**
		 * Initializes the upload runtime.
		 *
		 * @method init
		 * @param {plupload.Uploader} uploader Uploader instance that needs to be initialized.
		 * @param {function} callback Callback to execute when the runtime initializes or fails to initialize. If it succeeds an object with a parameter name success will be set to true.
		 */
		init : function(uploader, callback) {
			var desktop;

			// Check for gears support
			if (!window.google || !google.gears) {
				return callback({success : false});
			}

			try {
				desktop = google.gears.factory.create('beta.desktop');
			} catch (e) {
				// Might fail on the latest Gecko build for some odd reason
				return callback({success : false});
			}

			function addSelectedFiles(selected_files) {
				var file, i, files = [], id;

				// Add the selected files to the file queue
				for (i = 0; i < selected_files.length; i++) {
					file = selected_files[i];

					// Store away gears blob internally
					id = plupload.guid();
					blobs[id] = file.blob;

					files.push(new plupload.File(id, file.name, file.blob.length));
				}

				// Fire FilesAdded event
				uploader.trigger("FilesAdded", files);
			}

			// Add drop handler
			uploader.bind("PostInit", function() {
				var settings = uploader.settings, dropElm = document.getElementById(settings.drop_element);

				if (dropElm) {
					// Block browser default drag over
					plupload.addEvent(dropElm, 'dragover', function(e) {
						desktop.setDropEffect(e, 'copy');
						e.preventDefault();
					});

					// Attach drop handler and grab files from Gears
					plupload.addEvent(dropElm, 'drop', function(e) {
						var dragData = desktop.getDragData(e, 'application/x-gears-files');

						if (dragData) {
							addSelectedFiles(dragData.files);
						}

						e.preventDefault();
					});

					// Prevent IE leak
					dropElm = 0;
				}

				// Add browse button
				plupload.addEvent(document.getElementById(settings.browse_button), 'click', function(e) {
					var filters = [], i, a, ext;

					e.preventDefault();

					for (i = 0; i < settings.filters.length; i++) {
						ext = settings.filters[i].extensions.split(',');

						for (a = 0; a < ext.length; a++) {
							filters.push('.' + ext[a]);
						}
					}

					desktop.openFiles(addSelectedFiles, {singleFile : !settings.multi_selection, filter : filters});
				});
			});

			uploader.bind("UploadFile", function(up, file) {
				var chunk = 0, chunks, chunkSize, loaded = 0, resize = up.settings.resize, chunking;

				chunkSize = up.settings.chunk_size;
				chunking = chunkSize > 0;
				chunks = Math.ceil(file.size / chunkSize);

				// If chunking is disabled then upload the whole file in one huge chunk
				if (!chunking) {
					chunkSize = file.size;
					chunks = 1;
				}

				// If file is png or jpeg and resize is configured then resize it
				if (resize && /\.(png|jpg|jpeg)$/i.test(file.name)) {
					blobs[file.id] = scaleImage(blobs[file.id], resize.width, resize.height, resize.quality || 90, /\.png$/i.test(file.name) ? 'image/png' : 'image/jpeg');
				}

				file.size = blobs[file.id].length;

				function uploadNextChunk() {
					var req, curChunkSize, multipart = up.settings.multipart, multipartLength = 0, reqArgs = {name : file.target_name || file.name}, url = up.settings.url;

					// Sends the binary blob multipart encoded or raw depending on config
					function sendBinaryBlob(blob) {
						var builder, boundary = '----pluploadboundary' + plupload.guid(), dashdash = '--', crlf = '\r\n', multipartBlob, mimeType;

						// Build multipart request
						if (multipart) {
							req.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
							builder = google.gears.factory.create('beta.blobbuilder');

							// Append mutlipart parameters
							plupload.each(plupload.extend(reqArgs, up.settings.multipart_params), function(value, name) {
								builder.append(
									dashdash + boundary + crlf +
									'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf
								);

								builder.append(value + crlf);
							});

							mimeType = plupload.mimeTypes[file.name.replace(/^.+\.([^.]+)/, '$1')] || 'application/octet-stream';

							// Add file header
							builder.append(
								dashdash + boundary + crlf +
								'Content-Disposition: form-data; name="' + up.settings.file_data_name + '"; filename="' + file.name + '"' + crlf +
								'Content-Type: ' + mimeType + crlf + crlf
							);

							// Add file data
							builder.append(blob);

							// Add footer
							builder.append(crlf + dashdash + boundary + dashdash + crlf);
							multipartBlob = builder.getAsBlob();
							multipartLength = multipartBlob.length - blob.length;
							blob = multipartBlob;
						}

						// Send blob or multipart blob depending on config
						req.send(blob);
					}

					// File upload finished
					if (file.status == plupload.DONE || file.status == plupload.FAILED || up.state == plupload.STOPPED) {
						return;
					}

					// Only add chunking args if needed
					if (chunking) {
						reqArgs.chunk = chunk;
						reqArgs.chunks = chunks;
					}

					// Setup current chunk size
					curChunkSize = Math.min(chunkSize, file.size - (chunk  * chunkSize));

					if (!multipart) {
						url = plupload.buildUrl(up.settings.url, reqArgs);
					}

					req = google.gears.factory.create('beta.httprequest');
					req.open('POST', url);

					// Add disposition and type if multipart is disabled
					if (!multipart) {
						req.setRequestHeader('Content-Disposition', 'attachment; filename="' + file.name + '"');
						req.setRequestHeader('Content-Type', 'application/octet-stream');
					}

					// Set custom headers
					plupload.each(up.settings.headers, function(value, name) {
						req.setRequestHeader(name, value);
					});

					req.upload.onprogress = function(progress) {
						file.loaded = loaded + progress.loaded - multipartLength;
						up.trigger('UploadProgress', file);
					};

					req.onreadystatechange = function() {
						var chunkArgs;

						if (req.readyState == 4) {
							if (req.status == 200) {
								chunkArgs = {
									chunk : chunk,
									chunks : chunks,
									response : req.responseText,
									status : req.status
								};

								up.trigger('ChunkUploaded', file, chunkArgs);

								// Stop upload
								if (chunkArgs.cancelled) {
									file.status = plupload.FAILED;
									return;
								}

								loaded += curChunkSize;

								if (++chunk >= chunks) {
									file.status = plupload.DONE;
									up.trigger('FileUploaded', file, {
										response : req.responseText,
										status : req.status
									});
								} else {
									uploadNextChunk();
								}
							} else {
								up.trigger('Error', {
									code : plupload.HTTP_ERROR,
									message : 'HTTP Error.',
									file : file,
									chunk : chunk,
									chunks : chunks,
									status : req.status
								});
							}
						}
					};

					if (chunk < chunks) {
						sendBinaryBlob(blobs[file.id].slice(chunk * chunkSize, curChunkSize));
					}
				}

				// Start uploading chunks
				uploadNextChunk();
			});

			callback({success : true});
		}
	});
})(plupload);
<commit_msg>Moved the chunk size calculations to be done after images are scaled.<commit_after>/**
 * plupload.gears.js
 *
 * Copyright 2009, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

// JSLint defined globals
/*global plupload:false, google:false, window:false */

(function(plupload) {
	var blobs = {};

	function scaleImage(image_blob, width, height, quality, mime) {
		var percentage, canvas, context, scale;

		// Setup canvas and scale
		canvas = google.gears.factory.create('beta.canvas');
		try {
			canvas.decode(image_blob);
			scale = Math.min(width / canvas.width, height / canvas.height);

			if (scale < 1) {
				canvas.resize(Math.round(canvas.width * scale), Math.round(canvas.height * scale));

				return canvas.encode(mime, {quality : quality / 100});
			}
		} catch (e) {
			// Ignore for example when a user uploads a file that can't be decoded
		}

		return image_blob;
	}

	/**
	 * Gears implementation. This runtime supports these features: dragdrop, jpgresize, pngresize, chunks.
	 *
	 * @static
	 * @class plupload.runtimes.Gears
	 * @extends plupload.Runtime
	 */
	plupload.runtimes.Gears = plupload.addRuntime("gears", {
		/**
		 * Returns a list of supported features for the runtime.
		 *
		 * @return {Object} Name/value object with supported features.
		 */
		getFeatures : function() {
			return {
				dragdrop: true,
				jpgresize: true,
				pngresize: true,
				chunks: true,
				progress: true,
				multipart: true
			};
		},

		/**
		 * Initializes the upload runtime.
		 *
		 * @method init
		 * @param {plupload.Uploader} uploader Uploader instance that needs to be initialized.
		 * @param {function} callback Callback to execute when the runtime initializes or fails to initialize. If it succeeds an object with a parameter name success will be set to true.
		 */
		init : function(uploader, callback) {
			var desktop;

			// Check for gears support
			if (!window.google || !google.gears) {
				return callback({success : false});
			}

			try {
				desktop = google.gears.factory.create('beta.desktop');
			} catch (e) {
				// Might fail on the latest Gecko build for some odd reason
				return callback({success : false});
			}

			function addSelectedFiles(selected_files) {
				var file, i, files = [], id;

				// Add the selected files to the file queue
				for (i = 0; i < selected_files.length; i++) {
					file = selected_files[i];

					// Store away gears blob internally
					id = plupload.guid();
					blobs[id] = file.blob;

					files.push(new plupload.File(id, file.name, file.blob.length));
				}

				// Fire FilesAdded event
				uploader.trigger("FilesAdded", files);
			}

			// Add drop handler
			uploader.bind("PostInit", function() {
				var settings = uploader.settings, dropElm = document.getElementById(settings.drop_element);

				if (dropElm) {
					// Block browser default drag over
					plupload.addEvent(dropElm, 'dragover', function(e) {
						desktop.setDropEffect(e, 'copy');
						e.preventDefault();
					});

					// Attach drop handler and grab files from Gears
					plupload.addEvent(dropElm, 'drop', function(e) {
						var dragData = desktop.getDragData(e, 'application/x-gears-files');

						if (dragData) {
							addSelectedFiles(dragData.files);
						}

						e.preventDefault();
					});

					// Prevent IE leak
					dropElm = 0;
				}

				// Add browse button
				plupload.addEvent(document.getElementById(settings.browse_button), 'click', function(e) {
					var filters = [], i, a, ext;

					e.preventDefault();

					for (i = 0; i < settings.filters.length; i++) {
						ext = settings.filters[i].extensions.split(',');

						for (a = 0; a < ext.length; a++) {
							filters.push('.' + ext[a]);
						}
					}

					desktop.openFiles(addSelectedFiles, {singleFile : !settings.multi_selection, filter : filters});
				});
			});

			uploader.bind("UploadFile", function(up, file) {
				var chunk = 0, chunks, chunkSize, loaded = 0, resize = up.settings.resize, chunking;

				// If file is png or jpeg and resize is configured then resize it
				if (resize && /\.(png|jpg|jpeg)$/i.test(file.name)) {
					blobs[file.id] = scaleImage(blobs[file.id], resize.width, resize.height, resize.quality || 90, /\.png$/i.test(file.name) ? 'image/png' : 'image/jpeg');
				}

				file.size = blobs[file.id].length;

				chunkSize = up.settings.chunk_size;
				chunking = chunkSize > 0;
				chunks = Math.ceil(file.size / chunkSize);

				// If chunking is disabled then upload the whole file in one huge chunk
				if (!chunking) {
					chunkSize = file.size;
					chunks = 1;
				}

				function uploadNextChunk() {
					var req, curChunkSize, multipart = up.settings.multipart, multipartLength = 0, reqArgs = {name : file.target_name || file.name}, url = up.settings.url;

					// Sends the binary blob multipart encoded or raw depending on config
					function sendBinaryBlob(blob) {
						var builder, boundary = '----pluploadboundary' + plupload.guid(), dashdash = '--', crlf = '\r\n', multipartBlob, mimeType;

						// Build multipart request
						if (multipart) {
							req.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
							builder = google.gears.factory.create('beta.blobbuilder');

							// Append mutlipart parameters
							plupload.each(plupload.extend(reqArgs, up.settings.multipart_params), function(value, name) {
								builder.append(
									dashdash + boundary + crlf +
									'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf
								);

								builder.append(value + crlf);
							});

							mimeType = plupload.mimeTypes[file.name.replace(/^.+\.([^.]+)/, '$1')] || 'application/octet-stream';

							// Add file header
							builder.append(
								dashdash + boundary + crlf +
								'Content-Disposition: form-data; name="' + up.settings.file_data_name + '"; filename="' + file.name + '"' + crlf +
								'Content-Type: ' + mimeType + crlf + crlf
							);

							// Add file data
							builder.append(blob);

							// Add footer
							builder.append(crlf + dashdash + boundary + dashdash + crlf);
							multipartBlob = builder.getAsBlob();
							multipartLength = multipartBlob.length - blob.length;
							blob = multipartBlob;
						}

						// Send blob or multipart blob depending on config
						req.send(blob);
					}

					// File upload finished
					if (file.status == plupload.DONE || file.status == plupload.FAILED || up.state == plupload.STOPPED) {
						return;
					}

					// Only add chunking args if needed
					if (chunking) {
						reqArgs.chunk = chunk;
						reqArgs.chunks = chunks;
					}

					// Setup current chunk size
					curChunkSize = Math.min(chunkSize, file.size - (chunk  * chunkSize));

					if (!multipart) {
						url = plupload.buildUrl(up.settings.url, reqArgs);
					}

					req = google.gears.factory.create('beta.httprequest');
					req.open('POST', url);

					// Add disposition and type if multipart is disabled
					if (!multipart) {
						req.setRequestHeader('Content-Disposition', 'attachment; filename="' + file.name + '"');
						req.setRequestHeader('Content-Type', 'application/octet-stream');
					}

					// Set custom headers
					plupload.each(up.settings.headers, function(value, name) {
						req.setRequestHeader(name, value);
					});

					req.upload.onprogress = function(progress) {
						file.loaded = loaded + progress.loaded - multipartLength;
						up.trigger('UploadProgress', file);
					};

					req.onreadystatechange = function() {
						var chunkArgs;

						if (req.readyState == 4) {
							if (req.status == 200) {
								chunkArgs = {
									chunk : chunk,
									chunks : chunks,
									response : req.responseText,
									status : req.status
								};

								up.trigger('ChunkUploaded', file, chunkArgs);

								// Stop upload
								if (chunkArgs.cancelled) {
									file.status = plupload.FAILED;
									return;
								}

								loaded += curChunkSize;

								if (++chunk >= chunks) {
									file.status = plupload.DONE;
									up.trigger('FileUploaded', file, {
										response : req.responseText,
										status : req.status
									});
								} else {
									uploadNextChunk();
								}
							} else {
								up.trigger('Error', {
									code : plupload.HTTP_ERROR,
									message : 'HTTP Error.',
									file : file,
									chunk : chunk,
									chunks : chunks,
									status : req.status
								});
							}
						}
					};

					if (chunk < chunks) {
						sendBinaryBlob(blobs[file.id].slice(chunk * chunkSize, curChunkSize));
					}
				}

				// Start uploading chunks
				uploadNextChunk();
			});

			callback({success : true});
		}
	});
})(plupload);
<|endoftext|>


<commit_before>$.fn.droppy = function() {

  this.each(function() {

    var root = this, zIndex = 1000;

    function getSubnav(ele) {
      if (ele.nodeName.toLowerCase() == 'li') {
        var subnav = $('> ul', ele);
        return subnav.length ? subnav[0] : null;
      } else {
        return ele;
      }
    }

    function getActuator(ele) {
      if (ele.nodeName.toLowerCase() == 'ul') {
        return $(ele).parents('li')[0];
      } else {
        return ele;
      }
    }

    function hide() {
      var subnav = getSubnav(this);
      if (!subnav) return;
      $.data(subnav, 'cancelHide', false);
      setTimeout(function() {
        if (!$.data(subnav, 'cancelHide')) {
          $(subnav).slideUp();
        }
      }, 500);
    }

    function show() {
      var subnav = getSubnav(this);
      if (!subnav) return;
      $.data(subnav, 'cancelHide', true);
      $(subnav).css({zIndex: zIndex++}).slideDown();
      if (this.nodeName.toLowerCase() == 'ul') {
        $(getActuator(this)).addClass('hover');
      }
    }

    $('ul, li', this).hover(show, hide);
    $('li', this).hover(
      function() { $(this).addClass('hover'); },
      function() { $(this).removeClass('hover'); }
    );

  });

};
<commit_msg>made animation speed configurable<commit_after>$.fn.droppy = function(options) {

  options = $.extend({speed: 250}, options || {});

  this.each(function() {

    var root = this, zIndex = 1000;

    function getSubnav(ele) {
      if (ele.nodeName.toLowerCase() == 'li') {
        var subnav = $('> ul', ele);
        return subnav.length ? subnav[0] : null;
      } else {
        return ele;
      }
    }

    function getActuator(ele) {
      if (ele.nodeName.toLowerCase() == 'ul') {
        return $(ele).parents('li')[0];
      } else {
        return ele;
      }
    }

    function hide() {
      var subnav = getSubnav(this);
      if (!subnav) return;
      $.data(subnav, 'cancelHide', false);
      setTimeout(function() {
        if (!$.data(subnav, 'cancelHide')) {
          $(subnav).slideUp(options.speed);
        }
      }, 500);
    }

    function show() {
      var subnav = getSubnav(this);
      if (!subnav) return;
      $.data(subnav, 'cancelHide', true);
      $(subnav).css({zIndex: zIndex++}).slideDown(options.speed);
      if (this.nodeName.toLowerCase() == 'ul') {
        $(getActuator(this)).addClass('hover');
      }
    }

    $('ul, li', this).hover(show, hide);
    $('li', this).hover(
      function() { $(this).addClass('hover'); },
      function() { $(this).removeClass('hover'); }
    );

  });

};
<|endoftext|>


<commit_before>import { lib } from './lib';
import { applyEnums, createTypedBuffer, elementContext, Fail, GetArray,
         GetBoolValue, GetStringArray, GetHandle, wcb } from './helpers';
import { PCardinal, PByte } from './types';

// ENUMERATIONS
const conflictThis = ['ctUnknown', 'ctIgnored', 'ctNotDefined', 'ctIdenticalToMaster', 'ctOnlyOne', 'ctHiddenByModGroup', 'ctMaster', 'ctConflictBenign', 'ctOverride', 'ctIdenticalToMasterWinsConflict', 'ctConflictWins', 'ctConflictLoses'];
const conflictAll = ['caUnknown', 'caOnlyOne', 'caNoConflict', 'caConflictBenign', 'caOverride', 'caConflict', 'caConflictCritical'];

applyEnums(xelib, conflictThis, 'conflictThis');
applyEnums(xelib, conflictAll, 'conflictAll');

// RECORD HANDLING METHODS
Object.assign(xelib, {
    GetFormID: function(_id, local = false) {
        let _res = createTypedBuffer(4, PCardinal);
        if (!lib.GetFormID(_id, _res, local))
            Fail(`Failed to get FormID for ${_id}`);
        return _res.readUInt32LE();
    },
    GetHexFormID: function(_id, local = false) {
        return xelib.Hex(xelib.GetFormID(_id, local));
    },
    SetFormID: function(_id, newFormID, local = false, fixReferences = true) {
        if (!lib.SetFormID(_id, newFormID, local, fixReferences))
            Fail(`Failed to set FormID on ${_id} to ${newFormID}`);
    },
    GetRecord: function(_id, formID) {
        return GetHandle(function(_res) {
            if (!lib.GetRecord(_id, formID, _res))
                Fail(`Failed to get record at: ${_id}, ${formID}`);
        });
    },
    GetRecords: function(_id, search, includeOverrides = false) {
        return GetArray(function(_len) {
            if (!lib.GetRecords(_id, wcb(search), includeOverrides, _len))
                Fail(`Failed to get records from: ${elementContext(_id, search)}`);
        });
    },
    GetOverrides: function(_id) {
        return GetArray(function(_len) {
            if (!lib.GetOverrides(_id, _len))
                Fail(`Failed to get overrides for: ${_id}`);
        });
    },
    GetMasterRecord: function(_id) {
        return GetHandle(function(_res) {
            if (!lib.GetMasterRecord(_id, _res))
                Fail(`Failed to get master record for: ${_id}`);
        });
    },
    GetPreviousOverride: function(_id, _id2) {
        return GetHandle(function(_res) {
            if (!lib.GetPreviousOverride(_id, _id2, _res))
                Fail(`Failed to get previous override record for: ${_id}, targetting file ${_id2}`);
        });
    },
    GetWinningOverride: function(_id) {
        return GetHandle(function(_res) {
            if (!lib.GetWinningOverride(_id, _res))
                Fail(`Failed to get winning override record for: ${_id}`);
        });
    },
    FindNextRecord: function(_id, search, byEdid, byName) {
        return GetHandle(function(_res) {
            lib.FindNextRecord(_id, wcb(search), byEdid, byName, _res);
        });
    },
    FindPreviousRecord: function(_id, search, byEdid, byName) {
        return GetHandle(function(_res) {
            lib.FindPreviousRecord(_id, wcb(search), byEdid, byName, _res);
        });
    },
    FindValidReferences: function(_id, signature, search, limitTo) {
        return GetStringArray(function(_len) {
            if (!lib.FindValidReferences(_id, wcb(signature), wcb(search), limitTo, _len))
                Fail(`Failed to find valid ${signature} references on ${_id} searching for: ${search}`);
        });
    },
    GetReferencedBy: function(_id) {
        return GetArray(function(_len) {
            if (!lib.GetReferencedBy(_id, _len))
                Fail(`Failed to get referenced by for: ${_id}`);
        });
    },
    ExchangeReferences: function(_id, oldFormID, newFormID) {
        if (!lib.ExchangeReferences(_id, oldFormID, newFormID))
            Fail(`Failed to exchange references on ${_id} from ${oldFormID} to ${newFormID}`)
    },
    IsMaster: function(_id) {
        return GetBoolValue(_id, "IsMaster");
    },
    IsInjected: function(_id) {
        return GetBoolValue(_id, "IsInjected");
    },
    IsOverride: function(_id) {
        return GetBoolValue(_id, "IsOverride");
    },
    IsWinningOverride: function(_id) {
        return GetBoolValue(_id, "IsWinningOverride");
    },
    GetNodes: function(_id) {
        return GetHandle(function(_res) {
            if (!lib.GetNodes(_id, _res))
                Fail(`Failed to get nodes for ${_id}`);
        });
    },
    GetConflictData: function(_id1, _id2, asString = false) {
        let _res1 = createTypedBuffer(1, PByte),
            _res2 = createTypedBuffer(1, PByte);
        if (!lib.GetConflictData(_id1, _id2, _res1, _res2))
            return [0, 0];
        let n1 = _res1.readUInt8(0),
            n2 = _res2.readUInt8(0);
        return asString ? [conflictAll[n1], conflictThis[n2]] : [n1, n2];
    },
    GetConflictDataEx: function(_id1, _id2, asString = false) {
        let _res1 = createTypedBuffer(1, PByte),
            _res2 = createTypedBuffer(1, PByte);
        if (!lib.GetConflictData(_id1, _id2, _res1, _res2))
            Fail(`GetConflictData failed on ${_id1}, ${_id2}`);
        let n1 = _res1.readUInt8(0),
            n2 = _res2.readUInt8(0);
        return asString ? [conflictAll[n1], conflictThis[n2]] : [n1, n2];
    },
    GetRecordConflictData: function(_id) {
        let nodes = xelib.GetNodes(_id);
        try {
            return xelib.GetConflictDataEx(nodes, _id);
        } finally {
            xelib.ReleaseNodes(nodes);
        }
    },
    GetNodeElements: function(_id1, _id2) {
        return GetArray(function(_len) {
            if (!lib.GetNodeElements(_id1, _id2, _len))
                Fail(`GetNodeElements failed on ${_id1}, ${_id2}`);
        });
    }
});
<commit_msg>tweaked GetFormID, GetHexFormID, and SetHexFormID what we were calling "local" formIDs were really "file" or "native" formIDs, so I refactored the argument from `local` to `native`. added `local` argument which actually gets a local formID (local formID excludes load order prefix, is only valid on master records)<commit_after>import { lib } from './lib';
import { applyEnums, createTypedBuffer, elementContext, Fail, GetArray,
         GetBoolValue, GetStringArray, GetHandle, wcb } from './helpers';
import { PCardinal, PByte } from './types';

// ENUMERATIONS
const conflictThis = ['ctUnknown', 'ctIgnored', 'ctNotDefined', 'ctIdenticalToMaster', 'ctOnlyOne', 'ctHiddenByModGroup', 'ctMaster', 'ctConflictBenign', 'ctOverride', 'ctIdenticalToMasterWinsConflict', 'ctConflictWins', 'ctConflictLoses'];
const conflictAll = ['caUnknown', 'caOnlyOne', 'caNoConflict', 'caConflictBenign', 'caOverride', 'caConflict', 'caConflictCritical'];

applyEnums(xelib, conflictThis, 'conflictThis');
applyEnums(xelib, conflictAll, 'conflictAll');

// RECORD HANDLING METHODS
Object.assign(xelib, {
    GetFormID: function(_id, native = false, local = false) {
        let _res = createTypedBuffer(4, PCardinal);
        if (!lib.GetFormID(_id, _res, native))
            Fail(`Failed to get FormID for ${_id}`);
        let formID = _res.readUInt32LE();
        return local ? formID & 0xFFFFFF : formID;
    },
    GetHexFormID: function(_id, native = false, local = false) {
        return xelib.Hex(xelib.GetFormID(_id, native, local), local ? 6 : 8);
    },
    SetFormID: function(_id, newFormID, native = false, fixReferences = true) {
        if (!lib.SetFormID(_id, newFormID, local, fixReferences))
            Fail(`Failed to set FormID on ${_id} to ${newFormID}`);
    },
    GetRecord: function(_id, formID) {
        return GetHandle(function(_res) {
            if (!lib.GetRecord(_id, formID, _res))
                Fail(`Failed to get record at: ${_id}, ${formID}`);
        });
    },
    GetRecords: function(_id, search, includeOverrides = false) {
        return GetArray(function(_len) {
            if (!lib.GetRecords(_id, wcb(search), includeOverrides, _len))
                Fail(`Failed to get records from: ${elementContext(_id, search)}`);
        });
    },
    GetOverrides: function(_id) {
        return GetArray(function(_len) {
            if (!lib.GetOverrides(_id, _len))
                Fail(`Failed to get overrides for: ${_id}`);
        });
    },
    GetMasterRecord: function(_id) {
        return GetHandle(function(_res) {
            if (!lib.GetMasterRecord(_id, _res))
                Fail(`Failed to get master record for: ${_id}`);
        });
    },
    GetPreviousOverride: function(_id, _id2) {
        return GetHandle(function(_res) {
            if (!lib.GetPreviousOverride(_id, _id2, _res))
                Fail(`Failed to get previous override record for: ${_id}, targetting file ${_id2}`);
        });
    },
    GetWinningOverride: function(_id) {
        return GetHandle(function(_res) {
            if (!lib.GetWinningOverride(_id, _res))
                Fail(`Failed to get winning override record for: ${_id}`);
        });
    },
    FindNextRecord: function(_id, search, byEdid, byName) {
        return GetHandle(function(_res) {
            lib.FindNextRecord(_id, wcb(search), byEdid, byName, _res);
        });
    },
    FindPreviousRecord: function(_id, search, byEdid, byName) {
        return GetHandle(function(_res) {
            lib.FindPreviousRecord(_id, wcb(search), byEdid, byName, _res);
        });
    },
    FindValidReferences: function(_id, signature, search, limitTo) {
        return GetStringArray(function(_len) {
            if (!lib.FindValidReferences(_id, wcb(signature), wcb(search), limitTo, _len))
                Fail(`Failed to find valid ${signature} references on ${_id} searching for: ${search}`);
        });
    },
    GetReferencedBy: function(_id) {
        return GetArray(function(_len) {
            if (!lib.GetReferencedBy(_id, _len))
                Fail(`Failed to get referenced by for: ${_id}`);
        });
    },
    ExchangeReferences: function(_id, oldFormID, newFormID) {
        if (!lib.ExchangeReferences(_id, oldFormID, newFormID))
            Fail(`Failed to exchange references on ${_id} from ${oldFormID} to ${newFormID}`)
    },
    IsMaster: function(_id) {
        return GetBoolValue(_id, "IsMaster");
    },
    IsInjected: function(_id) {
        return GetBoolValue(_id, "IsInjected");
    },
    IsOverride: function(_id) {
        return GetBoolValue(_id, "IsOverride");
    },
    IsWinningOverride: function(_id) {
        return GetBoolValue(_id, "IsWinningOverride");
    },
    GetNodes: function(_id) {
        return GetHandle(function(_res) {
            if (!lib.GetNodes(_id, _res))
                Fail(`Failed to get nodes for ${_id}`);
        });
    },
    GetConflictData: function(_id1, _id2, asString = false) {
        let _res1 = createTypedBuffer(1, PByte),
            _res2 = createTypedBuffer(1, PByte);
        if (!lib.GetConflictData(_id1, _id2, _res1, _res2))
            return [0, 0];
        let n1 = _res1.readUInt8(0),
            n2 = _res2.readUInt8(0);
        return asString ? [conflictAll[n1], conflictThis[n2]] : [n1, n2];
    },
    GetConflictDataEx: function(_id1, _id2, asString = false) {
        let _res1 = createTypedBuffer(1, PByte),
            _res2 = createTypedBuffer(1, PByte);
        if (!lib.GetConflictData(_id1, _id2, _res1, _res2))
            Fail(`GetConflictData failed on ${_id1}, ${_id2}`);
        let n1 = _res1.readUInt8(0),
            n2 = _res2.readUInt8(0);
        return asString ? [conflictAll[n1], conflictThis[n2]] : [n1, n2];
    },
    GetRecordConflictData: function(_id) {
        let nodes = xelib.GetNodes(_id);
        try {
            return xelib.GetConflictDataEx(nodes, _id);
        } finally {
            xelib.ReleaseNodes(nodes);
        }
    },
    GetNodeElements: function(_id1, _id2) {
        return GetArray(function(_len) {
            if (!lib.GetNodeElements(_id1, _id2, _len))
                Fail(`GetNodeElements failed on ${_id1}, ${_id2}`);
        });
    }
});
<|endoftext|>


<commit_before>/*! jquery.taboverride.escape v0.1.0-dev | https://github.com/wjbryant/taboverride.escape
Copyright (c) 2013 Bill Bryant | http://opensource.org/licenses/mit */

/*global exports, require, define, jQuery, tabOverride */

/**
 * the global jQuery object
 *
 * @name jQuery
 * @namespace
 */

/**
 * the jQuery prototype shortcut "namespace"
 *
 * @name fn
 * @namespace
 * @memberOf jQuery
 */

// Use CommonJS or AMD if available
(function ( factory ) {
	"use strict";

	if ( typeof exports === "object" && typeof require === "function" ) {
		// Node.js/CommonJS
		factory( require( "jquery" ), require( "taboverride" ),
			require( "jquery.taboverride" ), require( "taboverride.escape" ) );
	} else if ( typeof define === "function" && define.amd ) {
		// AMD - Register as an anonymous module
		// Files must be concatenated using an AMD-aware tool such as r.js
		define( [ "jquery", "taboverride", "jquery.taboverride", "taboverride.escape" ], factory );
	} else {
		// No module format - Use global variables instead
		factory( jQuery, tabOverride );
	}
}(function ( $, tabOverride ) {
	"use strict";

	var $fnTabOverride = $.fn.tabOverride;

	$fnTabOverride.escape = tabOverride.escape;

	$fnTabOverride.addExtension( "setDelegated", function ( $container, selector, enable ) {
		$container.off( ".tabOverrideEscape", selector );

		if ( enable ) {
			$container.on({
				"keydown.tabOverrideEscape": function (e) {
					if ( $fnTabOverride.escape() && e.originalEvent.keyCode === 27 ) {
						$fnTabOverride.utils.removeDelegatedListeners( $container, selector );
					}
				},
				"blur.tabOverrideEscape": function () {
					$fnTabOverride.utils.addDelegatedListeners( $container, selector );
				}
			}, selector );
		}
	});
}));
<commit_msg>use tabOverride.addExtension()<commit_after>/*! jquery.taboverride.escape v0.1.0-dev | https://github.com/wjbryant/taboverride.escape
Copyright (c) 2013 Bill Bryant | http://opensource.org/licenses/mit */

/*global exports, require, define, jQuery, tabOverride */

/**
 * the global jQuery object
 *
 * @name jQuery
 * @namespace
 */

/**
 * the jQuery prototype shortcut "namespace"
 *
 * @name fn
 * @namespace
 * @memberOf jQuery
 */

// Use CommonJS or AMD if available
(function ( factory ) {
	"use strict";

	if ( typeof exports === "object" && typeof require === "function" ) {
		// Node.js/CommonJS
		factory( require( "jquery" ), require( "taboverride" ),
			require( "jquery.taboverride" ), require( "taboverride.escape" ) );
	} else if ( typeof define === "function" && define.amd ) {
		// AMD - Register as an anonymous module
		// Files must be concatenated using an AMD-aware tool such as r.js
		define( [ "jquery", "taboverride", "jquery.taboverride", "taboverride.escape" ], factory );
	} else {
		// No module format - Use global variables instead
		factory( jQuery, tabOverride );
	}
}(function ( $, tabOverride ) {
	"use strict";

	var $fnTabOverride = $.fn.tabOverride;

	$fnTabOverride.escape = tabOverride.escape;

	tabOverride.addExtension( "setDelegated", function ( $container, selector, enable ) {
		$container.off( ".tabOverrideEscape", selector );

		if ( enable ) {
			$container.on({
				"keydown.tabOverrideEscape": function (e) {
					if ( $fnTabOverride.escape() && e.originalEvent.keyCode === 27 ) {
						$fnTabOverride.utils.removeDelegatedListeners( $container, selector );
					}
				},
				"blur.tabOverrideEscape": function () {
					$fnTabOverride.utils.addDelegatedListeners( $container, selector );
				}
			}, selector );
		}
	});
}));
<|endoftext|>


<commit_before>// (C) Copyright 2014 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import KeyboardAccelerators from '../utils/KeyboardAccelerators';
import Drop from '../utils/Drop';
import { findAncestor } from '../utils/DOM';
import Button from './Button';

import SearchIcon from './icons/base/Search';

const CLASS_ROOT = "search-input";

export default class SearchInput extends Component {

  constructor(props) {
    super(props);

    this._onInputChange = this._onInputChange.bind(this);
    this._onAddDrop = this._onAddDrop.bind(this);
    this._onRemoveDrop = this._onRemoveDrop.bind(this);
    this._onNextSuggestion = this._onNextSuggestion.bind(this);
    this._onPreviousSuggestion = this._onPreviousSuggestion.bind(this);
    this._onEnter = this._onEnter.bind(this);
    this._onClickSuggestion = this._onClickSuggestion.bind(this);
    this._onFocus = this._onFocus.bind(this);

    this.state = {
      dropActive: false,
      defaultValue: props.defaultValue,
      value: props.value,
      activeSuggestionIndex: -1
    };
  }

  componentDidUpdate (prevProps, prevState) {
    // Set up keyboard listeners appropriate to the current state.

    var activeKeyboardHandlers = {
      esc: this._onRemoveDrop,
      tab: this._onRemoveDrop,
      up: this._onPreviousSuggestion,
      down: this._onNextSuggestion,
      enter: this._onEnter
    };
    var focusedKeyboardHandlers = {
      down: this._onAddDrop
    };

    // the order here is important, need to turn off keys before turning on

    if (! this.state.focused && prevState.focused) {
      KeyboardAccelerators.stopListeningToKeyboard(this, focusedKeyboardHandlers);
    }

    if (! this.state.dropActive && prevState.dropActive) {
      document.removeEventListener('click', this._onRemoveDrop);
      KeyboardAccelerators.stopListeningToKeyboard(this, activeKeyboardHandlers);
      if (this._drop) {
        this._drop.remove();
        this._drop = null;
      }
    }

    if (this.state.focused && ! prevState.focused) {
      KeyboardAccelerators.startListeningToKeyboard(this, focusedKeyboardHandlers);
    }

    if (this.state.dropActive && ! prevState.dropActive) {
      document.addEventListener('click', this._onRemoveDrop);
      KeyboardAccelerators.startListeningToKeyboard(this, activeKeyboardHandlers);

      // If this is inside a FormField, place the drop in reference to it.
      const control =
        findAncestor(this.refs.component, 'form-field') || this.refs.component;
      this._drop = Drop.add(control,
        this._renderDrop(), { align: {top: 'bottom', left: 'left'} });
    } else if (this.state.dropActive && prevState.dropActive) {
      this._drop.render(this._renderDrop());
    }
  }

  componentWillUnmount () {
    document.removeEventListener('click', this._onRemoveDrop);
    if (this._drop) {
      this._drop.remove();
    }
  }

  _fireDOMChange () {
    let event;
    try {
      event = new Event('change', {
        'bubbles': true,
        'cancelable': true
      });
    } catch (e) {
      // IE11 workaround.
      event = document.createEvent('Event');
      event.initEvent('change', true, true);
    }
    // We use dispatchEvent to have the browser fill out the event fully.
    this.refs.input.dispatchEvent(event);
    // Manually dispatched events aren't delivered by React, so we notify too.
    this.props.onDOMChange(event);
  }

  _onInputChange (event) {
    this.setState({dropActive: true, activeSuggestionIndex: -1});
    if (this.props.onChange) {
      this.props.onChange(event.target.value, false);
    }
    if (this.props.onDOMChange) {
      this._fireDOMChange();
    }
  }

  _onAddDrop (event) {
    event.preventDefault();
    this.setState({dropActive: true, activeSuggestionIndex: -1});
  }

  _onRemoveDrop () {
    this.setState({dropActive: false});
  }

  _onNextSuggestion () {
    var index = this.state.activeSuggestionIndex;
    index = Math.min(index + 1, this.props.suggestions.length - 1);
    this.setState({activeSuggestionIndex: index});
  }

  _onPreviousSuggestion () {
    var index = this.state.activeSuggestionIndex;
    index = Math.max(index - 1, 0);
    this.setState({activeSuggestionIndex: index});
  }

  _onEnter (event) {
    event.preventDefault(); // prevent submitting forms
    this.setState({dropActive: false});
    if (this.state.activeSuggestionIndex >= 0) {
      var suggestion = this.props.suggestions[this.state.activeSuggestionIndex];
      this.setState({value: suggestion});
      if (this.props.onChange) {
        this.props.onChange(suggestion, true);
      }
      if (this.props.onSelect) {
        this.props.onSelect({target: this.refs.input, suggestion: suggestion});
      }
    }
  }

  _onClickSuggestion (suggestion) {
    this.setState({value: suggestion, dropActive: false});
    if (this.props.onChange) {
      this.props.onChange(suggestion, true);
    }
    if (this.props.onSelect) {
      this.props.onSelect({target: this.refs.input, suggestion: suggestion});
    }
  }

  _onFocus () {
    this.setState({
      focused: true,
      activeSuggestionIndex: -1
    });
    // delay to wait out subsequent render after state change
    setTimeout(() => {
      this.refs.input.select();
    }, 10);
  }

  _renderLabel (suggestion) {
    if (typeof suggestion === 'object') {
      return suggestion.label || suggestion.value;
    } else {
      return suggestion;
    }
  }

  _renderDrop () {
    var suggestions = null;
    if (this.props.suggestions) {
      suggestions = this.props.suggestions.map(function (suggestion, index) {
        var classes = [CLASS_ROOT + "__suggestion"];
        if (index === this.state.activeSuggestionIndex) {
          classes.push(CLASS_ROOT + "__suggestion--active");
        }
        return (

            {this._renderLabel(suggestion)}

        );
      }, this);
    }

    return (

        {suggestions}

    );
  }

  render () {
    var classes = [CLASS_ROOT];
    if (this.state.active) {
      classes.push(CLASS_ROOT + "--active");
    }
    if (this.props.className) {
      classes.push(this.props.className);
    }

    return (

        <input ref="input" className={CLASS_ROOT + "__input"}
          id={this.props.id} name={this.props.name}
          value={this._renderLabel(this.props.value)}
          defaultValue={this._renderLabel(this.props.defaultValue)}
          placeholder={this.props.placeHolder}
          onChange={this._onInputChange}
          onFocus={this._onFocus} />
        <Button className={CLASS_ROOT + "__control"} icon={<SearchIcon />}
          onClick={this._onAddDrop} />

    );
  }

}

SearchInput.propTypes = {
  defaultValue: PropTypes.oneOfType([
    PropTypes.shape({
      label: PropTypes.string,
      value: PropTypes.string
    }),
    PropTypes.string
  ]),
  id: PropTypes.string,
  name: PropTypes.string,
  onChange: PropTypes.func,
  onDOMChange: PropTypes.func,
  onSelect: PropTypes.func,
  placeHolder: PropTypes.string,
  suggestions: PropTypes.arrayOf(
    PropTypes.oneOfType([
      PropTypes.shape({
        label: PropTypes.node,
        value: PropTypes.any
      }),
      PropTypes.string
    ])
  ),
  value: PropTypes.oneOfType([
    PropTypes.shape({
      label: PropTypes.string,
      value: PropTypes.string
    }),
    PropTypes.string
  ])
};
<commit_msg>highlighting selected value in SearchInput suggestion drop: https://github.com/grommet/grommet/issues/396<commit_after>// (C) Copyright 2014 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import KeyboardAccelerators from '../utils/KeyboardAccelerators';
import Drop from '../utils/Drop';
import { findAncestor } from '../utils/DOM';
import Button from './Button';

import SearchIcon from './icons/base/Search';

const CLASS_ROOT = "search-input";

export default class SearchInput extends Component {

  constructor(props) {
    super(props);

    this._onInputChange = this._onInputChange.bind(this);
    this._onAddDrop = this._onAddDrop.bind(this);
    this._onRemoveDrop = this._onRemoveDrop.bind(this);
    this._onNextSuggestion = this._onNextSuggestion.bind(this);
    this._onPreviousSuggestion = this._onPreviousSuggestion.bind(this);
    this._onEnter = this._onEnter.bind(this);
    this._onClickSuggestion = this._onClickSuggestion.bind(this);
    this._onFocus = this._onFocus.bind(this);

    this.state = {
      dropActive: false,
      defaultValue: props.defaultValue,
      value: props.value,
      activeSuggestionIndex: -1
    };
  }

  componentDidUpdate (prevProps, prevState) {
    // Set up keyboard listeners appropriate to the current state.

    var activeKeyboardHandlers = {
      esc: this._onRemoveDrop,
      tab: this._onRemoveDrop,
      up: this._onPreviousSuggestion,
      down: this._onNextSuggestion,
      enter: this._onEnter
    };
    var focusedKeyboardHandlers = {
      down: this._onAddDrop
    };

    // the order here is important, need to turn off keys before turning on

    if (! this.state.focused && prevState.focused) {
      KeyboardAccelerators.stopListeningToKeyboard(this, focusedKeyboardHandlers);
    }

    if (! this.state.dropActive && prevState.dropActive) {
      document.removeEventListener('click', this._onRemoveDrop);
      KeyboardAccelerators.stopListeningToKeyboard(this, activeKeyboardHandlers);
      if (this._drop) {
        this._drop.remove();
        this._drop = null;
      }
    }

    if (this.state.focused && ! prevState.focused) {
      KeyboardAccelerators.startListeningToKeyboard(this, focusedKeyboardHandlers);
    }

    if (this.state.dropActive && ! prevState.dropActive) {
      document.addEventListener('click', this._onRemoveDrop);
      KeyboardAccelerators.startListeningToKeyboard(this, activeKeyboardHandlers);

      // If this is inside a FormField, place the drop in reference to it.
      const control =
        findAncestor(this.refs.component, 'form-field') || this.refs.component;
      this._drop = Drop.add(control,
        this._renderDrop(), { align: {top: 'bottom', left: 'left'} });
    } else if (this.state.dropActive && prevState.dropActive) {
      this._drop.render(this._renderDrop());
    }
  }

  componentWillUnmount () {
    document.removeEventListener('click', this._onRemoveDrop);
    if (this._drop) {
      this._drop.remove();
    }
  }

  _fireDOMChange () {
    let event;
    try {
      event = new Event('change', {
        'bubbles': true,
        'cancelable': true
      });
    } catch (e) {
      // IE11 workaround.
      event = document.createEvent('Event');
      event.initEvent('change', true, true);
    }
    // We use dispatchEvent to have the browser fill out the event fully.
    this.refs.input.dispatchEvent(event);
    // Manually dispatched events aren't delivered by React, so we notify too.
    this.props.onDOMChange(event);
  }

  _onInputChange (event) {
    this.setState({dropActive: true, activeSuggestionIndex: -1});
    if (this.props.onChange) {
      this.props.onChange(event.target.value, false);
    }
    if (this.props.onDOMChange) {
      this._fireDOMChange();
    }
  }

  _onAddDrop (event) {
    event.preventDefault();
    // Get values of suggestions, so we can highlight selected suggestion
    var suggestionValues = this.props.suggestions.map((suggestion) => {
      if (typeof suggestion === 'object') {
        return suggestion.value;
      } else {
        return suggestion;
      }
    });
    var activeSuggestionIndex = suggestionValues.indexOf(this.props.value);

    this.setState({
      dropActive: true,
      activeSuggestionIndex: activeSuggestionIndex
    });
  }

  _onRemoveDrop () {
    this.setState({dropActive: false});
  }

  _onNextSuggestion () {
    var index = this.state.activeSuggestionIndex;
    index = Math.min(index + 1, this.props.suggestions.length - 1);
    this.setState({activeSuggestionIndex: index});
  }

  _onPreviousSuggestion () {
    var index = this.state.activeSuggestionIndex;
    index = Math.max(index - 1, 0);
    this.setState({activeSuggestionIndex: index});
  }

  _onEnter (event) {
    event.preventDefault(); // prevent submitting forms
    this.setState({dropActive: false});
    if (this.state.activeSuggestionIndex >= 0) {
      var suggestion = this.props.suggestions[this.state.activeSuggestionIndex];
      this.setState({value: suggestion});
      if (this.props.onChange) {
        this.props.onChange(suggestion, true);
      }
      if (this.props.onSelect) {
        this.props.onSelect({target: this.refs.input, suggestion: suggestion});
      }
    }
  }

  _onClickSuggestion (suggestion) {
    this.setState({value: suggestion, dropActive: false});
    if (this.props.onChange) {
      this.props.onChange(suggestion, true);
    }
    if (this.props.onSelect) {
      this.props.onSelect({target: this.refs.input, suggestion: suggestion});
    }
  }

  _onFocus () {
    this.setState({
      focused: true,
      activeSuggestionIndex: -1
    });
    // delay to wait out subsequent render after state change
    setTimeout(() => {
      this.refs.input.select();
    }, 10);
  }

  _renderLabel (suggestion) {
    if (typeof suggestion === 'object') {
      return suggestion.label || suggestion.value;
    } else {
      return suggestion;
    }
  }

  _renderDrop () {
    var suggestions = null;
    if (this.props.suggestions) {
      suggestions = this.props.suggestions.map(function (suggestion, index) {
        var classes = [CLASS_ROOT + "__suggestion"];
        if (index === this.state.activeSuggestionIndex) {
          classes.push(CLASS_ROOT + "__suggestion--active");
        }
        return (

            {this._renderLabel(suggestion)}

        );
      }, this);
    }

    return (

        {suggestions}

    );
  }

  render () {
    var classes = [CLASS_ROOT];
    if (this.state.active) {
      classes.push(CLASS_ROOT + "--active");
    }
    if (this.props.className) {
      classes.push(this.props.className);
    }

    return (

        <input ref="input" className={CLASS_ROOT + "__input"}
          id={this.props.id} name={this.props.name}
          value={this._renderLabel(this.props.value)}
          defaultValue={this._renderLabel(this.props.defaultValue)}
          placeholder={this.props.placeHolder}
          onChange={this._onInputChange}
          onFocus={this._onFocus} />
        <Button className={CLASS_ROOT + "__control"} icon={<SearchIcon />}
          onClick={this._onAddDrop} />

    );
  }

}

SearchInput.propTypes = {
  defaultValue: PropTypes.oneOfType([
    PropTypes.shape({
      label: PropTypes.string,
      value: PropTypes.string
    }),
    PropTypes.string
  ]),
  id: PropTypes.string,
  name: PropTypes.string,
  onChange: PropTypes.func,
  onDOMChange: PropTypes.func,
  onSelect: PropTypes.func,
  placeHolder: PropTypes.string,
  suggestions: PropTypes.arrayOf(
    PropTypes.oneOfType([
      PropTypes.shape({
        label: PropTypes.node,
        value: PropTypes.any
      }),
      PropTypes.string
    ])
  ),
  value: PropTypes.oneOfType([
    PropTypes.shape({
      label: PropTypes.string,
      value: PropTypes.string
    }),
    PropTypes.string
  ])
};
<|endoftext|>


<commit_before>import { take, put, call, fork, select, takeEvery, all, cancel } from 'redux-saga/effects'
import { store } from "../store"
import EthereumService from "../services/ethereum/ethereum"
import { setConnection } from "../actions/connectionActions"
import { delay } from 'redux-saga'

export function* createNewConnection() {
  var connectionInstance = new EthereumService({ default: 'http' })
  yield put(setConnection(connectionInstance))
  connectionInstance.subcribe()

  var state = store.getState()
  var ethereum = state.connection.ethereum
  const watchConnectionTask = yield fork(watchToSwitchConnection, ethereum)

  yield take('GLOBAL.CLEAR_SESSION')
  yield cancel(watchConnectionTask)
}

function* watchToSwitchConnection(ethereum) {
  while (true) {
    try {
      yield call(delay, 10000)
      if (ethereum.currentLabel === "ws") {
        if (!ethereum.wsProvider.connection) {
          ethereum.setProvider(ethereum.httpProvider)
          ethereum.currentLabel = "http"
          ethereum.subcribe()
          yield put(setConnection(ethereum))
          // return
        }
      }

      if (ethereum.currentLabel === "http") {
        if (ethereum.wsProvider.reconnectTime > 10) {
          // yield put(clearIntervalConnection())
          return;
        }
        if (ethereum.wsProvider.connection) {
          ethereum.clearSubcription()
          ethereum.wsProvider.reconnectTime = 0

          ethereum.setProvider(ethereum.wsProvider)
          ethereum.currentLabel = "ws"
          ethereum.subcribe()
          yield put(setConnection(ethereum))
        } else {
          // increase reconnect time
          var reconnectTime = ethereum.wsProvider.reconnectTime
          ethereum.wsProvider = ethereum.getWebsocketProvider()
          ethereum.wsProvider.reconnectTime = reconnectTime + 1
          yield put(setConnection(ethereum))
        }
        // return
      }
    } catch (err) {
      console.log(err)
    }
  }
}

export function* watchConnection() {
  yield takeEvery("CONNECTION.CREATE_NEW_CONNECTION", createNewConnection)
}
<commit_msg>-fix connection<commit_after>import { take, put, call, fork, select, takeEvery, all, cancel } from 'redux-saga/effects'
import { store } from "../store"
import EthereumService from "../services/ethereum/ethereum"
import { setConnection } from "../actions/connectionActions"
import { delay } from 'redux-saga'

export function* createNewConnection() {
  var connectionInstance = new EthereumService({ default: 'http' })
  yield put(setConnection(connectionInstance))
  connectionInstance.subcribe()

  var state = store.getState()
  var ethereum = state.connection.ethereum
  const watchConnectionTask = yield fork(watchToSwitchConnection, ethereum)

  //yield take('GLOBAL.CLEAR_SESSION')
  //yield cancel(watchConnectionTask)
}

function* watchToSwitchConnection(ethereum) {
  while (true) {
    try {
      yield call(delay, 10000)
      if (ethereum.currentLabel === "ws") {
        if (!ethereum.wsProvider.connection) {
          ethereum.setProvider(ethereum.httpProvider)
          ethereum.currentLabel = "http"
          ethereum.subcribe()
          yield put(setConnection(ethereum))
          // return
        }
      }

      if (ethereum.currentLabel === "http") {
        if (ethereum.wsProvider.reconnectTime > 10) {
          // yield put(clearIntervalConnection())
          return;
        }
        if (ethereum.wsProvider.connection) {
          ethereum.clearSubcription()
          ethereum.wsProvider.reconnectTime = 0

          ethereum.setProvider(ethereum.wsProvider)
          ethereum.currentLabel = "ws"
          ethereum.subcribe()
          yield put(setConnection(ethereum))
        } else {
          // increase reconnect time
          var reconnectTime = ethereum.wsProvider.reconnectTime
          ethereum.wsProvider = ethereum.getWebsocketProvider()
          ethereum.wsProvider.reconnectTime = reconnectTime + 1
          yield put(setConnection(ethereum))
        }
        // return
      }
    } catch (err) {
      console.log(err)
    }
  }
}

export function* watchConnection() {
  yield takeEvery("CONNECTION.CREATE_NEW_CONNECTION", createNewConnection)
}
<|endoftext|>


<commit_before>var ContainerConstants = require("../constants/ContainerConstants");

var containerScheme = {
  "container": {
    "type": ContainerConstants.TYPE.DOCKER,
    "docker": {
      "image": null,
      "network": null,
      "portMappings": [
        {
          "containerPort": 0,
          "hostPort": 0,
          "servicePort": 0,
          "protocol": ContainerConstants.PORTMAPPINGS.PROTOCOL.TCP
        }
      ]
    },
    "privileged": false,
    "parameters": [],
    "forcePullImage": false,
    "volumes": []
  }
};

module.exports = containerScheme;
<commit_msg>Remov unused container scheme<commit_after><|endoftext|>


<commit_before>/**
 * Wheel, copyright (c) 2020 - present by Arno van der Vegt
 * Distributed under an MIT license: https://arnovandervegt.github.io/wheel/license.txt
**/
const platform = require('../../../../../shared/lib/platform');

exports.tab = (settingsDialog) => {
    return {
        ref:       settingsDialog.setRef('tabView'),
        className: 'abs max-w tab-panel ui1-box vscroll tab-view',
        children: [
            settingsDialog.addTitle('General'),
            settingsDialog.addCheckboxSetting({
                label:       'Dark mode',
                tabIndex:    1,
                getter:      'getDarkMode',
                signal:      'Settings.Set.DarkMode'
            }),
            settingsDialog.addHr(),
            settingsDialog.addTitle('Panels'),
            settingsDialog.addCheckboxSetting({
                label:       'Show files',
                tabIndex:    2,
                getter:      'getShowFileTree',
                signal:      'Settings.Set.ShowFileTree'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'Show console',
                tabIndex:    3,
                getter:      'getShowConsole',
                signal:      'Settings.Set.Console.Visible'
            }),
            settingsDialog.addCheckboxSetting({
                ref:         settingsDialog.setRef('showSimulator'),
                label:       'Show simulator',
                tabIndex:    4,
                getter:      'getShowSimulator',
                signal:      'Settings.Set.ShowSimulator',
                onChange:    (value) => {
                    if (value) {
                        let showProperties = settingsDialog.getRefs().showProperties;
                        if (showProperties.getChecked()) {
                            showProperties.setChecked(false);
                        }
                    }
                }
            }),
            settingsDialog.addCheckboxSetting({
                ref:         settingsDialog.setRef('showProperties'),
                label:       'Show component properties',
                tabIndex:    5,
                getter:      'getShowProperties',
                signal:      'Settings.Set.ShowProperties',
                onChange:    (value) => {
                    if (value) {
                        let showSimulator = settingsDialog.getRefs().showSimulator;
                        if (showSimulator.getChecked()) {
                            showSimulator.setChecked(false);
                        }
                    }
                }
            }),
            settingsDialog.addHr(),
            settingsDialog.addTitle('Simulator'),
            settingsDialog.addCheckboxSetting({
                label:       'Show simulator on run',
                tabIndex:    6,
                getter:      'getShowSimulatorOnRun',
                signal:      'Settings.Set.ShowSimulatorOnRun'
            }),
            settingsDialog.addHr(),
            settingsDialog.addTitle('Hidden hint dialogs'),
            settingsDialog.addCheckboxSetting({
                label:       'A form was openend but the property editor is not visible',
                tabIndex:    7,
                getter:      'getDontShowOpenForm',
                signal:      'Settings.Set.DontShowOpenForm'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'Connected to device but simulator is not visible',
                tabIndex:    8,
                getter:      'getDontShowConnected',
                signal:      'Settings.Set.DontShowConnected'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'Saving in local storage',
                tabIndex:    9,
                getter:      'getDontShowSave',
                signal:      'Settings.Set.DontShowSave'
            }),
            settingsDialog.addHr(),
            settingsDialog.addTitle('Home screen tiles'),
            settingsDialog.addCheckboxSetting({
                label:       'NXT connect tile',
                tabIndex:    10,
                getter:      'getShowNXTTile',
                signal:      'Settings.Set.ShowNXTTile'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'EV3 connect tile',
                tabIndex:    11,
                getter:      'getShowEV3Tile',
                signal:      'Settings.Set.ShowEV3Tile'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'EV3 image tile',
                tabIndex:    12,
                getter:      'getShowEV3ImageTile',
                signal:      'Settings.Set.ShowEV3ImageTile'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'Powered Up connect tile',
                tabIndex:    13,
                getter:      'getShowPoweredUpTile',
                signal:      'Settings.Set.ShowPoweredUpTile'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'Spike connect tile',
                tabIndex:    14,
                getter:      'getShowSpikeTile',
                signal:      'Settings.Set.ShowSpikeTile'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'New form tile',
                tabIndex:    15,
                getter:      'getShowNewFormTile',
                signal:      'Settings.Set.ShowNewFormTile'
            }),
            settingsDialog.addSpacer()
        ]
    };
};
<commit_msg>Only show save hint option for web version.<commit_after>/**
 * Wheel, copyright (c) 2020 - present by Arno van der Vegt
 * Distributed under an MIT license: https://arnovandervegt.github.io/wheel/license.txt
**/
const platform = require('../../../../../shared/lib/platform');

exports.tab = (settingsDialog) => {
    return {
        ref:       settingsDialog.setRef('tabView'),
        className: 'abs max-w tab-panel ui1-box vscroll tab-view',
        children: [
            settingsDialog.addTitle('General'),
            settingsDialog.addCheckboxSetting({
                label:       'Dark mode',
                tabIndex:    1,
                getter:      'getDarkMode',
                signal:      'Settings.Set.DarkMode'
            }),
            settingsDialog.addHr(),
            settingsDialog.addTitle('Panels'),
            settingsDialog.addCheckboxSetting({
                label:       'Show files',
                tabIndex:    2,
                getter:      'getShowFileTree',
                signal:      'Settings.Set.ShowFileTree'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'Show console',
                tabIndex:    3,
                getter:      'getShowConsole',
                signal:      'Settings.Set.Console.Visible'
            }),
            settingsDialog.addCheckboxSetting({
                ref:         settingsDialog.setRef('showSimulator'),
                label:       'Show simulator',
                tabIndex:    4,
                getter:      'getShowSimulator',
                signal:      'Settings.Set.ShowSimulator',
                onChange:    (value) => {
                    if (value) {
                        let showProperties = settingsDialog.getRefs().showProperties;
                        if (showProperties.getChecked()) {
                            showProperties.setChecked(false);
                        }
                    }
                }
            }),
            settingsDialog.addCheckboxSetting({
                ref:         settingsDialog.setRef('showProperties'),
                label:       'Show component properties',
                tabIndex:    5,
                getter:      'getShowProperties',
                signal:      'Settings.Set.ShowProperties',
                onChange:    (value) => {
                    if (value) {
                        let showSimulator = settingsDialog.getRefs().showSimulator;
                        if (showSimulator.getChecked()) {
                            showSimulator.setChecked(false);
                        }
                    }
                }
            }),
            settingsDialog.addHr(),
            settingsDialog.addTitle('Simulator'),
            settingsDialog.addCheckboxSetting({
                label:       'Show simulator on run',
                tabIndex:    6,
                getter:      'getShowSimulatorOnRun',
                signal:      'Settings.Set.ShowSimulatorOnRun'
            }),
            settingsDialog.addHr(),
            settingsDialog.addTitle('Hidden hint dialogs'),
            settingsDialog.addCheckboxSetting({
                label:       'A form was openend but the property editor is not visible',
                tabIndex:    7,
                getter:      'getDontShowOpenForm',
                signal:      'Settings.Set.DontShowOpenForm'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'Connected to device but simulator is not visible',
                tabIndex:    8,
                getter:      'getDontShowConnected',
                signal:      'Settings.Set.DontShowConnected'
            }),
            platform.isWeb() ?
                settingsDialog.addCheckboxSetting({
                    label:       'Saving in local storage',
                    tabIndex:    9,
                    getter:      'getDontShowSave',
                    signal:      'Settings.Set.DontShowSave'
                }) :
                null,
            settingsDialog.addHr(),
            settingsDialog.addTitle('Home screen tiles'),
            settingsDialog.addCheckboxSetting({
                label:       'NXT connect tile',
                tabIndex:    10,
                getter:      'getShowNXTTile',
                signal:      'Settings.Set.ShowNXTTile'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'EV3 connect tile',
                tabIndex:    11,
                getter:      'getShowEV3Tile',
                signal:      'Settings.Set.ShowEV3Tile'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'EV3 image tile',
                tabIndex:    12,
                getter:      'getShowEV3ImageTile',
                signal:      'Settings.Set.ShowEV3ImageTile'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'Powered Up connect tile',
                tabIndex:    13,
                getter:      'getShowPoweredUpTile',
                signal:      'Settings.Set.ShowPoweredUpTile'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'Spike connect tile',
                tabIndex:    14,
                getter:      'getShowSpikeTile',
                signal:      'Settings.Set.ShowSpikeTile'
            }),
            settingsDialog.addCheckboxSetting({
                label:       'New form tile',
                tabIndex:    15,
                getter:      'getShowNewFormTile',
                signal:      'Settings.Set.ShowNewFormTile'
            }),
            settingsDialog.addSpacer()
        ]
    };
};
<|endoftext|>


<commit_before>/*
* WRequiredIf 1.0
* Copyright (c) 2011 Webers
*
* Depends:
*   - jQuery 1.4.2+
*
* Dual licensed under MIT or GPLv2 licenses
*   http://en.wikipedia.org/wiki/MIT_License
*   http://en.wikipedia.org/wiki/GNU_General_Public_License
*
*/
$(function () {
    jQuery.validator.unobtrusive.adapters.add("wrequired", function (options) {
        // jQuery Validate equates "required" with "mandatory" for checkbox elements
        if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
            options.rules["wrequired"] = true;
            if (options.message) {
                options.messages["wrequired"] = options.message;
            }
        }
    });

    jQuery.validator.addMethod("wrequired", function (value, element, param) {
        return value != null && value != '';
    });
} (jQuery));<commit_msg>changed wrequired.unobstrusive.js from UTF-8 to ANSI<commit_after>/*
* WRequiredIf 1.0
* Copyright (c) 2011 Webers
*
* Depends:
*   - jQuery 1.4.2+
*
* Dual licensed under MIT or GPLv2 licenses
*   http://en.wikipedia.org/wiki/MIT_License
*   http://en.wikipedia.org/wiki/GNU_General_Public_License
*
*/
$(function () {
    jQuery.validator.unobtrusive.adapters.add("wrequired", function (options) {
        // jQuery Validate equates "required" with "mandatory" for checkbox elements
        if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
            options.rules.wrequired = true;
            if (options.message) {
                options.messages.wrequired = options.message;
            }
        }
    });

    jQuery.validator.addMethod("wrequired", function (value, element, param) {
        return value !== null && value !== undefined && value !== '';
    });
} (jQuery));<|endoftext|>