<commit_before>/**
Copyright (C) 2011 by Semmy Purewal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**/

var main = function () {
    /* TEMPORARY MESSAGE STUFF TILL WE GET VIEWS WORKED OUT */
    var messageTimeout = 5000;
    var messageTimer;

    var message = function(message)  {
        var messageEl = messageDiv[0];
        if(messageTimer)  {
            clearTimeout(messageTimer);
        }
        messageEl.setAttribute("style", "display:none");
        messageEl.firstChild?messageEl.firstChild.data=message:messageEl.appendChild(document.createTextNode(message));

        messageShow(messageEl);
        messageTimer = setTimeout(function()  {
            messageHide(messageEl);
        }, messageTimeout);
    };

    var messageOptions = function(options)  {
        if(options.show)  {
            messageShow = options.show;
        }
        if(options.hide)  {
            messageHide = options.hide;
        }
        if(options.time)  {
            messageTimeout = options.time;
        }
    }

    messageOptions({
        show:function(div)  {
            $(div).fadeIn();
        },
        hide:function(div)  {
            $(div).fadeOut();
        },
        time: 3000
    });
    /* END TEMPORARY MESSAGE STUFF */

    //set up ide model
    var ide = new window.IDE(new Project("examples/hello.json"));

    //add buttons
    ide.buttons().add(new Button("run", "images/icons/run.png", function () {
        ide.messages().add("running program");
        ide.project().source(ide.editor().getSession().getValue());
        message(ide.messages().at(ide.messages().size()-1));
        return false;
    }));

    //set up views
    var buttonTemplate = Handlebars.compile($("#button-template").html());
    var titleDiv = $("#IDE-title");
    var buttonsDiv = $("#IDE-buttons");
    var messageDiv = $("#IDE-message");
    var i, button;

    titleDiv.text(ide.project().title());

    var attachButtonView = function (b) {
        var button = $(buttonTemplate({ name:b.name(), img:b.imageURL() }));
        button.click(function () { b.handler()(); });
        $(buttonsDiv).append(button);
    }

    for (i = 0; i < ide.buttons().size(); i++) {
        attachButtonView(ide.buttons().at(i));
    }

    //RUN BUTTON CODE
    var p;  //processing object
    var error;  //processing error

    $("#IDE-run_button").colorbox({
        'title' : ide.project().title(),
        'inline' : true,
        'href':"#canvas",
        'onLoad' : function()  {
            var code = ide.project().source();
            var canvas = document.getElementById("processing_canvas");
            error = null;

            try  {
                p = new Processing(canvas, code);
                var dimensions = code.match(/\s+size\((\d+),(\d+)\)/);
                var width = parseInt(dimensions[1]);
                var height = parseInt(dimensions[2]);
                $("#processing_canvas").css('width',width);
                $("#processing_canvas").css('height',height);
            }
            catch(err)  {
                error = err;
                Processing.logger.log(err);
                if(p)  {
                    p.exit();
                }
            }
        },

        'onComplete' : function()  {
            if(error)  {
                console.log(error);
                $.colorbox.close();
            } else  {
                $("#processing_canvas").focus();
            }
        },
        'onCleanup' : function()  {
            if(p)  {
                p.exit();
            }
        }
    });
    //END RUN BUTTON CODE
};

$(document).ready(function()  {
    main();
});
<commit_msg>removes a single redundant line from main.js<commit_after>/**
Copyright (C) 2011 by Semmy Purewal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**/

var main = function () {
    /* TEMPORARY MESSAGE STUFF TILL WE GET VIEWS WORKED OUT */
    var messageTimeout = 5000;
    var messageTimer;

    var message = function(message)  {
        var messageEl = messageDiv[0];
        if(messageTimer)  {
            clearTimeout(messageTimer);
        }
        messageEl.setAttribute("style", "display:none");
        messageEl.firstChild?messageEl.firstChild.data=message:messageEl.appendChild(document.createTextNode(message));

        messageShow(messageEl);
        messageTimer = setTimeout(function()  {
            messageHide(messageEl);
        }, messageTimeout);
    };

    var messageOptions = function(options)  {
        if(options.show)  {
            messageShow = options.show;
        }
        if(options.hide)  {
            messageHide = options.hide;
        }
        if(options.time)  {
            messageTimeout = options.time;
        }
    }

    messageOptions({
        show:function(div)  {
            $(div).fadeIn();
        },
        hide:function(div)  {
            $(div).fadeOut();
        },
        time: 3000
    });
    /* END TEMPORARY MESSAGE STUFF */

    //set up ide model
    var ide = new window.IDE(new Project("examples/hello.json"));

    //add buttons
    ide.buttons().add(new Button("run", "images/icons/run.png", function () {
        ide.messages().add("running program");
        ide.project().source(ide.editor().getSession().getValue());
        message(ide.messages().at(ide.messages().size()-1));
        return false;
    }));

    //set up views
    var buttonTemplate = Handlebars.compile($("#button-template").html());
    var titleDiv = $("#IDE-title");
    var buttonsDiv = $("#IDE-buttons");
    var messageDiv = $("#IDE-message");
    var i, button;

    var attachButtonView = function (b) {
        var button = $(buttonTemplate({ name:b.name(), img:b.imageURL() }));
        button.click(function () { b.handler()(); });
        $(buttonsDiv).append(button);
    }

    for (i = 0; i < ide.buttons().size(); i++) {
        attachButtonView(ide.buttons().at(i));
    }

    //RUN BUTTON CODE
    var p;  //processing object
    var error;  //processing error

    $("#IDE-run_button").colorbox({
        'title' : ide.project().title(),
        'inline' : true,
        'href':"#canvas",
        'onLoad' : function()  {
            var code = ide.project().source();
            var canvas = document.getElementById("processing_canvas");
            error = null;

            try  {
                p = new Processing(canvas, code);
                var dimensions = code.match(/\s+size\((\d+),(\d+)\)/);
                var width = parseInt(dimensions[1]);
                var height = parseInt(dimensions[2]);
                $("#processing_canvas").css('width',width);
                $("#processing_canvas").css('height',height);
            }
            catch(err)  {
                error = err;
                Processing.logger.log(err);
                if(p)  {
                    p.exit();
                }
            }
        },

        'onComplete' : function()  {
            if(error)  {
                console.log(error);
                $.colorbox.close();
            } else  {
                $("#processing_canvas").focus();
            }
        },
        'onCleanup' : function()  {
            if(p)  {
                p.exit();
            }
        }
    });
    //END RUN BUTTON CODE
};

$(document).ready(function()  {
    main();
});
<|endoftext|>


<commit_before>/*
 * Konami-JS
 * http://snaptortoise.com/konami-js
 * Copyright (c) 2009 George Mandis (georgemandis.com)
 * Version: 1.0 (04/27/2009)
 * Licensed under the Artistic License/GPL
 * http://dev.perl.org/licenses/
 * Tested in: Safari 4, Firefox 3, IE7
 */

var konami = {
	input:"",
	pattern:"3838404037393739666513",
	clear:setTimeout('konami.clear_input()',2000),
	load: function(link) {
		window.document.onkeydown = function(e) {
			konami.input+= e ? e.keyCode : event.keyCode;
			if (konami.input == konami.pattern) {
				konami.code(link);
				clearTimeout(konami.clear);
				return;
				}
			clearTimeout(konami.clear);
			konami.clear = setTimeout("konami.clear_input()",2000);
			}
	},
	code: function(link) { window.location=link},
	clear_input: function() {
		konami.input="";
		clearTimeout(konami.clear);
	}
}
<commit_msg>Update date and version number in comments. I just like pushing changes.<commit_after>/*
 * Konami-JS
 * http://snaptortoise.com/konami-js
 * Copyright (c) 2009 George Mandis (georgemandis.com)
 * Version: 1.0.8 (05/08/2009)
 * Licensed under the Artistic License/GPL
 * http://dev.perl.org/licenses/
 * Tested in: Safari 4, Firefox 3, IE7
 */

var konami = {
	input:"",
	pattern:"3838404037393739666513",
	clear:setTimeout('konami.clear_input()',2000),
	load: function(link) {
		window.document.onkeydown = function(e) {
			konami.input+= e ? e.keyCode : event.keyCode;
			if (konami.input == konami.pattern) {
				konami.code(link);
				clearTimeout(konami.clear);
				return;
				}
			clearTimeout(konami.clear);
			konami.clear = setTimeout("konami.clear_input()",2000);
			}
	},
	code: function(link) { window.location=link},
	clear_input: function() {
		konami.input="";
		clearTimeout(konami.clear);
	}
}
<|endoftext|>


<commit_before>// sum.js
<commit_msg>Implemented sum method<commit_after>// sum.js

function sum(a, b) {
  return a + b;
}

module.exports = sum;
<|endoftext|>


<commit_before>#!/usr/bin/env node

var child_process = require('child_process');
var fs = require('fs');
var optimist = require('optimist');

var argv = optimist
  .usage('Usage: depict URL OUT_FILE [OPTIONS]')
  .options('h', {
    alias: 'help',
    describe: 'Display help',
    default: false
  })
  .options('s', {
    alias: 'selector',
    describe: 'CSS selector',
    default: 'body'
  })
  .options('c', {
    alias: 'css',
    describe: 'CSS file to include in rendering',
    default: false
  })
  .check(function(argv) {
    if (argv._.length !== 2) throw new Error('URL and OUT_FILE must be given.');
  })
  .argv;

if (argv.h || argv.help) return optimist.showHelp();

var url = argv._[0];
var selector = argv.s || argv.selector;
var out_file = argv._[1];

var css_file = argv.c || argv.css;
var css_text = '';
if (css_file) {
    css_text = fs.readFileSync(css_file, 'utf8');
}

var args = [__dirname + '/depict-casperjs.js', url, selector, out_file];

if (css_text) {
    args.push('--css', css_text);
}

casper = child_process.spawn('casperjs', args);

casper.stdout.on('data', function(data) {
    process.stdout.write(data);
});

<commit_msg>Added hide-selector option<commit_after>#!/usr/bin/env node

var child_process = require('child_process');
var fs = require('fs');
var optimist = require('optimist');

var argv = optimist
  .usage('Usage: depict URL OUT_FILE [OPTIONS]')
  .options('h', {
    alias: 'help',
    describe: 'Display help',
    default: false
  })
  .options('s', {
    alias: 'selector',
    describe: 'CSS selector',
    default: 'body'
  })
  .options('c', {
    alias: 'css',
    describe: 'CSS file to include in rendering',
    default: false
  })
  .options('H', {
    alias: 'hide-selector',
    describe: 'Hide attributes of this selector berore rendering.',
    default: false
  })
  .check(function(argv) {
    if (argv._.length !== 2) throw new Error('URL and OUT_FILE must be given.');
  })
  .argv;

if (argv.h || argv.help) return optimist.showHelp();

var url = argv._[0];
var selector = argv.s || argv.selector;
var out_file = argv._[1];

var css_file = argv.c || argv.css;
var css_text = '';
if (css_file) {
    css_text = fs.readFileSync(css_file, 'utf8');
}

var hide_selector = argv.H || argv["hide-selector"];
if (hide_selector) {
  css_text += "\n\n " + hide_selector + " { display: none; }\n";
}

var args = [__dirname + '/depict-casperjs.js', url, selector, out_file];

if (css_text) {
    args.push('--css', css_text);
}

casper = child_process.spawn('casperjs', args);

casper.stdout.on('data', function(data) {
    process.stdout.write(data);
});

<|endoftext|>


<commit_before>/*
 * Simple jQuery Dialog
 * https://github.com/filamentgroup/dialog
 *
 * Copyright (c) 2013 Filament Group, Inc.
 * Author: @scottjehl
 * Contributors: @johnbender, @zachleat
 * Licensed under the MIT, GPL licenses.
 */

window.jQuery = window.jQuery || window.shoestring;

(function( w, $ ){
	w.componentNamespace = w.componentNamespace || w;

	var pluginName = "dialog", cl, ev,
		doc = w.document,
		docElem = doc.documentElement,
		body = doc.body,
		$html = $( docElem );

	var Dialog = w.componentNamespace.Dialog = function( element ){
		this.$el = $( element );

		// prevent double init
		if( this.$el.data( pluginName ) ){
			return this.$el.data( pluginName );
		}

		// record init
		this.$el.data( pluginName, this );

		// keeping data-nobg here for compat. Deprecated.
		this.$background = !this.$el.is( '[data-' + pluginName + '-nobg]' ) ?
			$( doc.createElement('div') ).addClass( cl.bkgd ).attr( "tabindex", "-1" ).appendTo( "body") :
			$( [] );

		// when dialog first inits, save a reference to the initial hash so we can know whether
		// there's room in the history stack to go back or not when closing
		this.initialLocationHash = w.location.hash;

		// the dialog's url hash is different from the dialog's actual ID attribute
		// this is because pairing the ID directly makes the browser jump to the top
		// of the dialog, rather than allowing us to space it off the top of the
		// viewport. also, if the dialog has a data-history attr, this property will
		// prevent its findability for onload and hashchanges
		this.nohistory =
			this.$el.attr( 'data-dialog-history' ) === "false" || !Dialog.history;

		// use the identifier and an extra tag for hash management
		this.hash = this.$el.attr( "id" ) + "-dialog";

		// if won't pop up the dialog on initial load (`nohistory`) the user MAY
		// refresh a url with the dialog id as the hash then a change of the hash
		// won't be recognized by the browser when the dialog comes up and the back
		// button will return to the referring page. So, when nohistory is defined,
		// we append a "unique" identifier to the hash.
		this.hash += this.nohistory ? "-" + Date.now().toString() : "" ;

		this.isOpen = false;
		this.isTransparentBackground = this.$el.is( '[data-transbg]' );

		this._addA11yAttrs();
	};

  // default to tracking history with the dialog
  Dialog.history = true;

	Dialog.events = ev = {
		open: pluginName + "-open",
		opened: pluginName + "-opened",
		close: pluginName + "-close",
		closed: pluginName + "-closed"
	};

	Dialog.classes = cl = {
		open: pluginName + "-open",
		opened: pluginName + "-opened",
		content: pluginName + "-content",
		close: pluginName + "-close",
		closed: pluginName + "-closed",
		bkgd: pluginName + "-background",
		bkgdOpen: pluginName + "-background-open",
		bkgdTrans: pluginName + "-background-trans"
	};

	Dialog.selectors = {
		close: "." + Dialog.classes.close + ", [data-close], [data-dialog-close]"
	};

	Dialog.prototype.destroy = function() {
		// unregister the focus stealing
		window.focusRegistry.unregister(this);

		this.$el.trigger("destroy");

		// clear init for this dom element
		this.$el.data()[pluginName] = undefined;

		// remove the backdrop for the dialog
		this.$background.remove();
	};

	Dialog.prototype.checkFocus = function(event){
		var $target = $( event.target );
		var shouldSteal;

		shouldSteal =
			this.isOpen &&
			!$target.closest( this.$el[0]).length &&
			this.isLastDialog() &&
			!this._isNonInteractive();

		return shouldSteal;
	};

	Dialog.prototype.stealFocus = function(){
		this.$el[0].focus();
	};

	Dialog.prototype._addA11yAttrs = function(){
		this.$el
			.attr( "role", "dialog" )
			.attr( "tabindex", "-1" )
			.find( Dialog.selectors.close ).attr( "role", "button" );

	};

	Dialog.prototype._removeA11yAttrs = function(){
		this.$el.removeAttr( "role" );
		this.$el.removeAttr( "tabindex" );
	};

	Dialog.prototype._isNonInteractive = function(){
		var computedDialog = window.getComputedStyle( this.$el[ 0 ], null );
		var closeLink = this.$el.find( Dialog.selectors.close )[0];
		var computedCloseLink;
		if( closeLink ){
			computedCloseLink = window.getComputedStyle( closeLink, null );
		}
		var computedBackground = window.getComputedStyle( this.$background[ 0 ], null );
		return computedDialog.getPropertyValue( "display" ) !== "none" &&
			computedDialog.getPropertyValue( "visibility" ) !== "hidden" &&
			( !computedCloseLink || computedCloseLink.getPropertyValue( "display" ) === "none" ) &&
			computedBackground.getPropertyValue( "display" ) === "none";
	};

	Dialog.prototype._checkInteractivity = function(){
		if( this._isNonInteractive() ){
			this._removeA11yAttrs();
			this._ariaShowUnrelatedElems();
		}
		else{
			this._addA11yAttrs();

		}
	};

	Dialog.prototype._ariaHideUnrelatedElems = function(){
		this._ariaShowUnrelatedElems();
		var ignoredElems = "script, style";
		var hideList = this.$el.siblings().not( ignoredElems );
		this.$el.parents().not( "body, html" ).each(function(){
			hideList = hideList.add( $( this ).siblings().not( ignoredElems ) );
		});
		hideList.each(function(){
			var priorHidden = $( this ).attr( "aria-hidden" ) || "";
			$( this )
				.attr( "data-dialog-aria-hidden", priorHidden )
				.attr( "aria-hidden", "true" );
		});
	};

	Dialog.prototype._ariaShowUnrelatedElems = function(){
		$( "[data-dialog-aria-hidden]" ).each(function(){
			if( $( this ).attr( "data-dialog-aria-hidden" ).match( "true|false" ) ){
				$( this ).attr( "aria-hidden", $( this ).attr( "data-dialog-aria-hidden" ) );
			}
			else {
				$( this ).removeAttr( "aria-hidden" );
			}
		}).removeAttr( "data-dialog-aria-hidden" );
	};

	Dialog.prototype.open = function() {
		if( this.isOpen ){
			return;
		}

		if( this.$background.length ) {
			this.$background[ 0 ].style.height = Math.max( docElem.scrollHeight, docElem.clientHeight ) + "px";
		}
		this.$el.addClass( cl.open );
		this.$background.addClass( cl.bkgdOpen );
		this.$background.attr( "id", this.$el.attr( "id" ) + "-background" );
		this._setBackgroundTransparency();

		this.scroll = "pageYOffset" in w ? w.pageYOffset : ( docElem.scrollY || docElem.scrollTop || ( body && body.scrollY ) || 0 );
		this.$el[ 0 ].style.top = this.scroll + "px";

		$html.addClass( cl.open );
		this.isOpen = true;

		var cleanHash = w.location.hash.replace( /^#/, "" );

		if( cleanHash.indexOf( "-dialog" ) > -1 && !this.isLastDialog() ){
			w.location.hash += "#" + this.hash;
		} else if( !this.isLastDialog() ){
			w.location.hash = this.hash;
		}

		if( doc.activeElement ){
			this.focused = doc.activeElement;
		}

		this.$el[ 0 ].focus();
		var self = this;
		setTimeout(function(){
			self._ariaHideUnrelatedElems();
		});

		this.$el.trigger( ev.opened );
	};

	Dialog.prototype.lastHash = function(){
		return w.location.hash.split( "#" ).pop();
	};

	// is this the newest/last dialog that was opened based on the hash
	Dialog.prototype.isLastDialog = function(){
		return this.lastHash() === this.hash;
	};

	Dialog.prototype._setBackgroundTransparency = function() {
		if( this.isTransparentBackground ){
			this.$background.addClass( cl.bkgdTrans );
		}
	};

	Dialog.prototype.close = function(){
		if( !this.isOpen ){
			return;
		}

		this._ariaShowUnrelatedElems();

		// if close() is called directly and the hash for this dialog is at the end
		// of the url, then we need to change the hash to remove it, either by going
		// back if we can, or by adding a history state that doesn't have it at the
		// end
		if( window.location.hash.split( "#" ).pop() === this.hash ){
			// check if we're back at the original hash, if we are then we can't
			// go back again otherwise we'll move away from the page
			var hashKeys = window.location.hash.split( "#" );
			var initialHashKeys = this.initialLocationHash.split( "#" );

			// if we are not at the original hash then use history
			// otherwise, if it's the same starting hash as it was at init time, we
			// can't trigger back to close the dialog, as it might take us elsewhere.
			// so we have to go forward and create a new hash that does not have this
			// dialog's hash at the end
			if( hashKeys.join("") !== initialHashKeys.join("") ){
				window.history.back();
			} else {
				var escapedRegexpHash = this
						.hash
						.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");

				window.location.hash = window
					.location
					.hash
					.replace( new RegExp( "#" + escapedRegexpHash + "$" ), "" );
			}

			return;
		}

		this.$el.removeClass( cl.open );

		this.$background.removeClass( cl.bkgdOpen );

		this.isOpen = false;

		// we only want to throw focus on close if we aren't
		// opening a nested dialog or some other UI state
		if( this.focused && !this.isLastDialog()){
				this.focused.focus();
		}
		if( $( "." + pluginName + "." + cl.open ).length === 0 ){
			$html.removeClass( cl.open );
			w.scrollTo( 0, this.scroll );
		}

		this.$el.trigger( ev.closed );
	};
}( this, window.jQuery ));
<commit_msg>new Date().getTime() more compatible<commit_after>/*
 * Simple jQuery Dialog
 * https://github.com/filamentgroup/dialog
 *
 * Copyright (c) 2013 Filament Group, Inc.
 * Author: @scottjehl
 * Contributors: @johnbender, @zachleat
 * Licensed under the MIT, GPL licenses.
 */

window.jQuery = window.jQuery || window.shoestring;

(function( w, $ ){
	w.componentNamespace = w.componentNamespace || w;

	var pluginName = "dialog", cl, ev,
		doc = w.document,
		docElem = doc.documentElement,
		body = doc.body,
		$html = $( docElem );

	var Dialog = w.componentNamespace.Dialog = function( element ){
		this.$el = $( element );

		// prevent double init
		if( this.$el.data( pluginName ) ){
			return this.$el.data( pluginName );
		}

		// record init
		this.$el.data( pluginName, this );

		// keeping data-nobg here for compat. Deprecated.
		this.$background = !this.$el.is( '[data-' + pluginName + '-nobg]' ) ?
			$( doc.createElement('div') ).addClass( cl.bkgd ).attr( "tabindex", "-1" ).appendTo( "body") :
			$( [] );

		// when dialog first inits, save a reference to the initial hash so we can know whether
		// there's room in the history stack to go back or not when closing
		this.initialLocationHash = w.location.hash;

		// the dialog's url hash is different from the dialog's actual ID attribute
		// this is because pairing the ID directly makes the browser jump to the top
		// of the dialog, rather than allowing us to space it off the top of the
		// viewport. also, if the dialog has a data-history attr, this property will
		// prevent its findability for onload and hashchanges
		this.nohistory =
			this.$el.attr( 'data-dialog-history' ) === "false" || !Dialog.history;

		// use the identifier and an extra tag for hash management
		this.hash = this.$el.attr( "id" ) + "-dialog";

		// if won't pop up the dialog on initial load (`nohistory`) the user MAY
		// refresh a url with the dialog id as the hash then a change of the hash
		// won't be recognized by the browser when the dialog comes up and the back
		// button will return to the referring page. So, when nohistory is defined,
		// we append a "unique" identifier to the hash.
		this.hash += this.nohistory ? "-" + new Date().getTime().toString() : "" ;

		this.isOpen = false;
		this.isTransparentBackground = this.$el.is( '[data-transbg]' );

		this._addA11yAttrs();
	};

  // default to tracking history with the dialog
  Dialog.history = true;

	Dialog.events = ev = {
		open: pluginName + "-open",
		opened: pluginName + "-opened",
		close: pluginName + "-close",
		closed: pluginName + "-closed"
	};

	Dialog.classes = cl = {
		open: pluginName + "-open",
		opened: pluginName + "-opened",
		content: pluginName + "-content",
		close: pluginName + "-close",
		closed: pluginName + "-closed",
		bkgd: pluginName + "-background",
		bkgdOpen: pluginName + "-background-open",
		bkgdTrans: pluginName + "-background-trans"
	};

	Dialog.selectors = {
		close: "." + Dialog.classes.close + ", [data-close], [data-dialog-close]"
	};

	Dialog.prototype.destroy = function() {
		// unregister the focus stealing
		window.focusRegistry.unregister(this);

		this.$el.trigger("destroy");

		// clear init for this dom element
		this.$el.data()[pluginName] = undefined;

		// remove the backdrop for the dialog
		this.$background.remove();
	};

	Dialog.prototype.checkFocus = function(event){
		var $target = $( event.target );
		var shouldSteal;

		shouldSteal =
			this.isOpen &&
			!$target.closest( this.$el[0]).length &&
			this.isLastDialog() &&
			!this._isNonInteractive();

		return shouldSteal;
	};

	Dialog.prototype.stealFocus = function(){
		this.$el[0].focus();
	};

	Dialog.prototype._addA11yAttrs = function(){
		this.$el
			.attr( "role", "dialog" )
			.attr( "tabindex", "-1" )
			.find( Dialog.selectors.close ).attr( "role", "button" );

	};

	Dialog.prototype._removeA11yAttrs = function(){
		this.$el.removeAttr( "role" );
		this.$el.removeAttr( "tabindex" );
	};

	Dialog.prototype._isNonInteractive = function(){
		var computedDialog = window.getComputedStyle( this.$el[ 0 ], null );
		var closeLink = this.$el.find( Dialog.selectors.close )[0];
		var computedCloseLink;
		if( closeLink ){
			computedCloseLink = window.getComputedStyle( closeLink, null );
		}
		var computedBackground = window.getComputedStyle( this.$background[ 0 ], null );
		return computedDialog.getPropertyValue( "display" ) !== "none" &&
			computedDialog.getPropertyValue( "visibility" ) !== "hidden" &&
			( !computedCloseLink || computedCloseLink.getPropertyValue( "display" ) === "none" ) &&
			computedBackground.getPropertyValue( "display" ) === "none";
	};

	Dialog.prototype._checkInteractivity = function(){
		if( this._isNonInteractive() ){
			this._removeA11yAttrs();
			this._ariaShowUnrelatedElems();
		}
		else{
			this._addA11yAttrs();

		}
	};

	Dialog.prototype._ariaHideUnrelatedElems = function(){
		this._ariaShowUnrelatedElems();
		var ignoredElems = "script, style";
		var hideList = this.$el.siblings().not( ignoredElems );
		this.$el.parents().not( "body, html" ).each(function(){
			hideList = hideList.add( $( this ).siblings().not( ignoredElems ) );
		});
		hideList.each(function(){
			var priorHidden = $( this ).attr( "aria-hidden" ) || "";
			$( this )
				.attr( "data-dialog-aria-hidden", priorHidden )
				.attr( "aria-hidden", "true" );
		});
	};

	Dialog.prototype._ariaShowUnrelatedElems = function(){
		$( "[data-dialog-aria-hidden]" ).each(function(){
			if( $( this ).attr( "data-dialog-aria-hidden" ).match( "true|false" ) ){
				$( this ).attr( "aria-hidden", $( this ).attr( "data-dialog-aria-hidden" ) );
			}
			else {
				$( this ).removeAttr( "aria-hidden" );
			}
		}).removeAttr( "data-dialog-aria-hidden" );
	};

	Dialog.prototype.open = function() {
		if( this.isOpen ){
			return;
		}

		if( this.$background.length ) {
			this.$background[ 0 ].style.height = Math.max( docElem.scrollHeight, docElem.clientHeight ) + "px";
		}
		this.$el.addClass( cl.open );
		this.$background.addClass( cl.bkgdOpen );
		this.$background.attr( "id", this.$el.attr( "id" ) + "-background" );
		this._setBackgroundTransparency();

		this.scroll = "pageYOffset" in w ? w.pageYOffset : ( docElem.scrollY || docElem.scrollTop || ( body && body.scrollY ) || 0 );
		this.$el[ 0 ].style.top = this.scroll + "px";

		$html.addClass( cl.open );
		this.isOpen = true;

		var cleanHash = w.location.hash.replace( /^#/, "" );

		if( cleanHash.indexOf( "-dialog" ) > -1 && !this.isLastDialog() ){
			w.location.hash += "#" + this.hash;
		} else if( !this.isLastDialog() ){
			w.location.hash = this.hash;
		}

		if( doc.activeElement ){
			this.focused = doc.activeElement;
		}

		this.$el[ 0 ].focus();
		var self = this;
		setTimeout(function(){
			self._ariaHideUnrelatedElems();
		});

		this.$el.trigger( ev.opened );
	};

	Dialog.prototype.lastHash = function(){
		return w.location.hash.split( "#" ).pop();
	};

	// is this the newest/last dialog that was opened based on the hash
	Dialog.prototype.isLastDialog = function(){
		return this.lastHash() === this.hash;
	};

	Dialog.prototype._setBackgroundTransparency = function() {
		if( this.isTransparentBackground ){
			this.$background.addClass( cl.bkgdTrans );
		}
	};

	Dialog.prototype.close = function(){
		if( !this.isOpen ){
			return;
		}

		this._ariaShowUnrelatedElems();

		// if close() is called directly and the hash for this dialog is at the end
		// of the url, then we need to change the hash to remove it, either by going
		// back if we can, or by adding a history state that doesn't have it at the
		// end
		if( window.location.hash.split( "#" ).pop() === this.hash ){
			// check if we're back at the original hash, if we are then we can't
			// go back again otherwise we'll move away from the page
			var hashKeys = window.location.hash.split( "#" );
			var initialHashKeys = this.initialLocationHash.split( "#" );

			// if we are not at the original hash then use history
			// otherwise, if it's the same starting hash as it was at init time, we
			// can't trigger back to close the dialog, as it might take us elsewhere.
			// so we have to go forward and create a new hash that does not have this
			// dialog's hash at the end
			if( hashKeys.join("") !== initialHashKeys.join("") ){
				window.history.back();
			} else {
				var escapedRegexpHash = this
						.hash
						.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");

				window.location.hash = window
					.location
					.hash
					.replace( new RegExp( "#" + escapedRegexpHash + "$" ), "" );
			}

			return;
		}

		this.$el.removeClass( cl.open );

		this.$background.removeClass( cl.bkgdOpen );

		this.isOpen = false;

		// we only want to throw focus on close if we aren't
		// opening a nested dialog or some other UI state
		if( this.focused && !this.isLastDialog()){
				this.focused.focus();
		}
		if( $( "." + pluginName + "." + cl.open ).length === 0 ){
			$html.removeClass( cl.open );
			w.scrollTo( 0, this.scroll );
		}

		this.$el.trigger( ev.closed );
	};
}( this, window.jQuery ));
<|endoftext|>


<commit_before>/*
 * servicer
 * Copyright (c) 2017 Icebob (https://github.com/icebob/servicer)
 * MIT Licensed
 */

"use strict";

const ExtendableError = require("es6-error");

/**
 * 'Service not found' Error message
 *
 * @class ServiceNotFoundError
 * @extends {Error}
 */
class ServiceNotFoundError extends ExtendableError {
	/**
	 * Creates an instance of ServiceNotFoundError.
	 *
	 * @param {any} message
	 *
	 * @memberOf ServiceNotFoundError
	 */
	constructor(message) {
		super(message);
	}
}

/**
 * 'Service not found' Error message
 *
 * @class RequestTimeoutError
 * @extends {Error}
 */
class RequestTimeoutError extends ExtendableError {
	/**
	 * Creates an instance of RequestTimeoutError.
	 *
	 * @param {any} data
	 * @param {any} nodeID
	 *
	 * @memberOf RequestTimeoutError
	 */
	constructor(data, nodeID) {
		super(`Request timed out when call '${data.action}' action on '${nodeID}' node!`);
		this.data = data;
	}
}

/**
 * 'Parameters of action call validation error
 *
 * @class ValidationError
 * @extends {Error}
 */
class ValidationError extends ExtendableError {
	/**
	 * Creates an instance of ValidationError.
	 *
	 * @param {any} message
	 * @param {any} data
	 *
	 * @memberOf ValidationError
	 */
	constructor(message, data) {
		super(message);
		if (data)
			this.data = data;
	}
}

module.exports = {
	ServiceNotFoundError,
	ValidationError,
	RequestTimeoutError
};<commit_msg>add error codes to custom errors<commit_after>/*
 * servicer
 * Copyright (c) 2017 Icebob (https://github.com/icebob/servicer)
 * MIT Licensed
 */

"use strict";

const ExtendableError = require("es6-error");

/**
 * 'Service not found' Error message
 *
 * @class ServiceNotFoundError
 * @extends {Error}
 */
class ServiceNotFoundError extends ExtendableError {
	/**
	 * Creates an instance of ServiceNotFoundError.
	 *
	 * @param {any} message
	 *
	 * @memberOf ServiceNotFoundError
	 */
	constructor(message) {
		super(message);
		this.code = 503;
	}
}

/**
 * 'Service not found' Error message
 *
 * @class RequestTimeoutError
 * @extends {Error}
 */
class RequestTimeoutError extends ExtendableError {
	/**
	 * Creates an instance of RequestTimeoutError.
	 *
	 * @param {any} data
	 * @param {any} nodeID
	 *
	 * @memberOf RequestTimeoutError
	 */
	constructor(data, nodeID) {
		super(`Request timed out when call '${data.action}' action on '${nodeID}' node!`);
		this.code = 408;
		this.data = data;
	}
}

/**
 * 'Parameters of action call validation error
 *
 * @class ValidationError
 * @extends {Error}
 */
class ValidationError extends ExtendableError {
	/**
	 * Creates an instance of ValidationError.
	 *
	 * @param {any} message
	 * @param {any} data
	 *
	 * @memberOf ValidationError
	 */
	constructor(message, data) {
		super(message);
		this.code = 422;
		if (data)
			this.data = data;
	}
}

module.exports = {
	ServiceNotFoundError,
	ValidationError,
	RequestTimeoutError
};<|endoftext|>


<commit_before>'use strict';
const slice = Array.prototype.slice;
const RESERVED = ',+"\\<>;';

function pad(str) {
  if (str.length < 2) return '0' + str;
  return str;
}

export default function escape(value) {
  if (value instanceof Buffer) {
    return '#' + value::slice().map(num => pad(num.toString(16))).join('');
  }
  let tokens = value.split('');
  let result = [];
  for (let i = 0; i < tokens.length; i++) {
    let token = tokens[i];
    if (RESERVED.indexOf(token) === -1) result.push(token);
    else result.push('\\' + token);
  }
  if (result[0] === '#') {
    result[0] = '\\#';
  } else if (result[0] === ' ') {
    let i;
    for (i = 1; i < result.length; i++) {
      if (result[i] !== ' ') break;
    }
    let head = result.splice(0, i);
    result.unshift(...head.map(ch => '\\' + ch));
  }
  let n = result.length;
  if (result[n - 1] === ' ') {
    let i;
    for (i = n - 2; i > 0; i--) {
      if (result[i] !== ' ') break;
    }
    let tail = result.splice(i + 1, n);
    result.push(...tail.map(ch => '\\' + ch));
  }
  return result.join('');
}
<commit_msg>More reserved characters. See https://msdn.microsoft.com/en-us/library/aa366101(v=vs.85).aspx<commit_after>'use strict';
const slice = Array.prototype.slice;
const RESERVED = ',+"\\<>;\n\r=/';

function pad(str) {
  if (str.length < 2) return '0' + str;
  return str;
}

export default function escape(value) {
  if (value instanceof Buffer) {
    return '#' + value::slice().map(num => pad(num.toString(16))).join('');
  }
  let tokens = value.split('');
  let result = [];
  for (let i = 0; i < tokens.length; i++) {
    let token = tokens[i];
    if (RESERVED.indexOf(token) === -1) result.push(token);
    else result.push('\\' + token);
  }
  if (result[0] === '#') {
    result[0] = '\\#';
  } else if (result[0] === ' ') {
    let i;
    for (i = 1; i < result.length; i++) {
      if (result[i] !== ' ') break;
    }
    let head = result.splice(0, i);
    result.unshift(...head.map(ch => '\\' + ch));
  }
  let n = result.length;
  if (result[n - 1] === ' ') {
    let i;
    for (i = n - 2; i > 0; i--) {
      if (result[i] !== ' ') break;
    }
    let tail = result.splice(i + 1, n);
    result.push(...tail.map(ch => '\\' + ch));
  }
  return result.join('');
}
<|endoftext|>


<commit_before>var eventsSeparatorMatch = /[,\s]+/g;

function registerEvent(node, eventName, callback) {
  callback.guid = ( callback.guid || guid++ );
  var eventCache = getData(node,'_cashEvents') || setData(node, '_cashEvents', {});
  eventCache[eventName] = eventCache[eventName] || [];
  eventCache[eventName].push(callback);
  node.addEventListener(eventName, callback);
}

function removeEventListeners(events, node, eventName) {
  each(events[eventName], callback => { node.removeEventListener(eventName, callback); });
  delete events[eventName];
}

function removeEvent(node, eventName, callback){
  var events = getData(node,'_cashEvents');
  if ( !events ) { return; }
  if ( eventName === undefined ) {
    for ( eventName in events ) {
      if ( !events.hasOwnProperty(eventName) ) { continue; }
      removeEventListeners(events,node,eventName);
    }
  } else {
    var eventCache = events[eventName];
    if ( !eventCache ) { return; }

    if (callback) {
      callback.guid = ( callback.guid || guid++ );
      events[eventName] = eventCache.filter ( cb => {
        if ( cb.guid !== callback.guid ) { return true; }
        node.removeEventListener(eventName, cb);
      });
    } else {
      removeEventListeners(events,node,eventName);
    }
  }
}

fn.extend({

  off(eventName, callback) {
    if ( eventName === undefined ) {
      this.each(v => removeEvent (v));
    } else {
      each( eventName.split(eventsSeparatorMatch), eventName => {
        this.each(v => removeEvent(v, eventName, callback) );
      });
    }
    return this;
  },

  on(eventName, delegate, callback, runOnce) { // jshint ignore:line

    if ( !isString(eventName) ) {
      for (var key in eventName) {
        this.on(key,delegate,eventName[key]);
      }
      return this;
    }

    if ( isFunction(delegate) ) {
      callback = delegate;
      delegate = null;
    }

    if ( eventName === 'ready' ) {
      onReady(callback);
      return this;
    }

    if ( delegate ) {
      var originalCallback = callback;
      callback = function(e) {
        var t = e.target;

        while (!matches(t, delegate)) {
          if (t === this) {
            return (t = false);
          }
          t = t.parentNode;
        }

        if (t) {
          originalCallback.call(t, e);
        }
      };
      callback.guid = originalCallback.guid = ( originalCallback.guid || guid++ );
    }

    each( eventName.split(eventsSeparatorMatch), eventName => {
      this.each(v => {
        var finalCallback = callback;
        if ( runOnce ) {
          finalCallback = function(){
            callback.apply(this,arguments);
            removeEvent(v, eventName, finalCallback);
          };
          finalCallback.guid = callback.guid;
        }
        registerEvent(v, eventName, finalCallback);
      });
    });
    return this;
  },

  one(eventName, delegate, callback) {
    return this.on(eventName, delegate, callback, true);
  },

  ready: onReady,

  trigger(eventName, data) {
    var evt = eventName;
    if (isString(eventName)) {
      evt = doc.createEvent('HTMLEvents');
      evt.initEvent(eventName, true, false);
    }
    evt.data = data;
    return this.each(v => v.dispatchEvent(evt));
  }

});
<commit_msg>$.fn.one: ensuring `callback.guid` is set<commit_after>var eventsSeparatorMatch = /[,\s]+/g;

function registerEvent(node, eventName, callback) {
  callback.guid = ( callback.guid || guid++ );
  var eventCache = getData(node,'_cashEvents') || setData(node, '_cashEvents', {});
  eventCache[eventName] = eventCache[eventName] || [];
  eventCache[eventName].push(callback);
  node.addEventListener(eventName, callback);
}

function removeEventListeners(events, node, eventName) {
  each(events[eventName], callback => { node.removeEventListener(eventName, callback); });
  delete events[eventName];
}

function removeEvent(node, eventName, callback){
  var events = getData(node,'_cashEvents');
  if ( !events ) { return; }
  if ( eventName === undefined ) {
    for ( eventName in events ) {
      if ( !events.hasOwnProperty(eventName) ) { continue; }
      removeEventListeners(events,node,eventName);
    }
  } else {
    var eventCache = events[eventName];
    if ( !eventCache ) { return; }

    if (callback) {
      callback.guid = ( callback.guid || guid++ );
      events[eventName] = eventCache.filter ( cb => {
        if ( cb.guid !== callback.guid ) { return true; }
        node.removeEventListener(eventName, cb);
      });
    } else {
      removeEventListeners(events,node,eventName);
    }
  }
}

fn.extend({

  off(eventName, callback) {
    if ( eventName === undefined ) {
      this.each(v => removeEvent (v));
    } else {
      each( eventName.split(eventsSeparatorMatch), eventName => {
        this.each(v => removeEvent(v, eventName, callback) );
      });
    }
    return this;
  },

  on(eventName, delegate, callback, runOnce) { // jshint ignore:line

    if ( !isString(eventName) ) {
      for (var key in eventName) {
        this.on(key,delegate,eventName[key]);
      }
      return this;
    }

    if ( isFunction(delegate) ) {
      callback = delegate;
      delegate = null;
    }

    if ( eventName === 'ready' ) {
      onReady(callback);
      return this;
    }

    if ( delegate ) {
      var originalCallback = callback;
      callback = function(e) {
        var t = e.target;

        while (!matches(t, delegate)) {
          if (t === this) {
            return (t = false);
          }
          t = t.parentNode;
        }

        if (t) {
          originalCallback.call(t, e);
        }
      };
      callback.guid = originalCallback.guid = ( originalCallback.guid || guid++ );
    }

    each( eventName.split(eventsSeparatorMatch), eventName => {
      this.each(v => {
        var finalCallback = callback;
        if ( runOnce ) {
          finalCallback = function(){
            callback.apply(this,arguments);
            removeEvent(v, eventName, finalCallback);
          };
          finalCallback.guid = callback.guid = ( callback.guid || guid++ );
        }
        registerEvent(v, eventName, finalCallback);
      });
    });
    return this;
  },

  one(eventName, delegate, callback) {
    return this.on(eventName, delegate, callback, true);
  },

  ready: onReady,

  trigger(eventName, data) {
    var evt = eventName;
    if (isString(eventName)) {
      evt = doc.createEvent('HTMLEvents');
      evt.initEvent(eventName, true, false);
    }
    evt.data = data;
    return this.each(v => v.dispatchEvent(evt));
  }

});
<|endoftext|>


<commit_before>import scene.ui.ButtonView as ButtonView;
import scene.ui.ProgressBar as ProgressBar;
import ui.ImageView as ImageView;
import ui.ScrollView as ScrollView;
import ui.resource.Image as Image;

var backgroundImage = new Image({url: 'resources/images/menuBg.png'});

exports = {
  setUp: function(positionX, positionY, w, h, png, view){
    var x = new ButtonView({
      superview: view,
      x: positionX,
      y: positionY,
      width: w,
      height: h,
      image: png
    });
    return x;
  },
  progressB: function(positionX, positionY, w, h, png, fImage){
    var b = new ProgressBar({
      superview: scene.ui,
      x: positionX,
      y: positionY,
      width: w,
      height: h,
      image: png,
      fillImage: fImage,
    });
    return b;
  },
  tabView: function(){
      var scrollView = new ScrollView({
      superview: scene.ui,
      x: 0,
      y: 750,
      bounce: false,
      width: scene.screen.width,
      height: 200,
      scrollX: false,
      scrollBounds: {
        minX: 0,
        maxX:backgroundImage.getWidth(),
        minY: 0,
        maxY: backgroundImage.getHeight()
      }
    });
      imageView = new ImageView({
        superview: scrollView,
        image: backgroundImage,
        width: backgroundImage.getWidth(),
        height: backgroundImage.getHeight()
    });

    return scrollView;
  }
}<commit_msg>Delete gameUI.js<commit_after><|endoftext|>


<commit_before>AddLayerClient = (function ()
{
    //var url ='http://10.0.10.184:8080/tilecache/accumuloProxy/wfs?request=GetFeature&typeName=tilecache:layers'
    //var url = "../json_3857.txt"; // For testing while not on RBT network
    var wfsURL;
    var layersArray = [];

    // This allows the client to request more tiles
    var tileUrls = [
        'http://s1:8080/tilecache/accumuloProxy/wms?',
        'http://s2:8080/tilecache/accumuloProxy/wms?',
        'http://s3:8080/tilecache/accumuloProxy/wms?',
        'http://s4:8080/tilecache/accumuloProxy/wms?'
    ];

    return {
        initialize: function ( addLayersClientParams )
        {
            wfsURL = addLayersClientParams.wfsURL;

            //var osmAwsAerialGroup = new ol.layer.Group( {
            //    layers: [
            //        new ol.layer.Tile( {
            //            style: 'Aerial',
            //            //visible: false,
            //            source: new ol.source.MapQuest( {layer: 'sat'} ),
            //            name: 'Aerial'
            //        } ),
            //        new ol.layer.Tile( {
            //            opacity: 1.0,
            //            source: new ol.source.TileWMS( {
            //                url: 'http://52.0.52.104/geoserver/ged/wms?',
            //                params: {'LAYERS': 'planet_osm_line', 'TILED': true}
            //            } ),
            //            name: 'Labels'
            //        } ),
            //        new ol.layer.Tile( {
            //            opacity: 1.0,
            //            source: new ol.source.TileWMS( {
            //                url: 'http://52.0.52.104/geoserver/ged/wms?',
            //                params: {'LAYERS': 'ne_10m_populated_places_all', 'TILED': true}
            //            } ),
            //            name: 'Place Names'
            //        } )
            //    ],
            //    name: 'Aerial and Labels'
            //} );

            var tileBoundsVectorSource = new ol.source.GeoJSON( {
                url: wfsURL,
                crossOrigin: 'anonymous',
                projection: 'EPSG:3857'
            } );

            // Tile sets extents layer
            //var tileBoundsVectorLayer = new ol.layer.Vector( {
            //    source: tileBoundsVectorSource,
            //    style: (function ()
            //    {
            //        var stroke = new ol.style.Stroke( {
            //            color: 'red',
            //            width: 5
            //        } );
            //        var textStroke = new ol.style.Stroke( {
            //            color: '#fff',
            //            width: 3
            //        } );
            //        var textFill = new ol.style.Fill( {
            //            color: 'red'
            //        } );
            //        return function ( feature, resolution )
            //        {
            //            return [new ol.style.Style( {
            //                stroke: stroke,
            //                text: new ol.style.Text( {
            //                    font: '36px Calibri,sans-serif',
            //                    text: 'Name: ' + feature.get( 'name' ) + ' Min: ' + feature.get( 'min_level' ) + ' Max: ' + feature.get( 'max_level' ),
            //                    fill: textFill,
            //                    stroke: textStroke
            //                } )
            //            } )];
            //        };
            //    })(),
            //    name: 'Tile Set Boundaries'
            //} );

            var resolutions = [156543.033928, 78271.5169639999, 39135.7584820001, 19567.8792409999, 9783.93962049996, 4891.96981024998, 2445.98490512499, 1222.99245256249, 611.49622628138, 305.748113140558, 152.874056570411, 76.4370282850732, 38.2185141425366, 19.1092570712683, 9.55462853563415, 4.77731426794937, 2.38865713397468, 1.19432856685505, 0.597164283559817, 0.298582141647617];

            var tileGrid = new ol.layer.Tile({
                source: new ol.source.TileDebug({
                    projection: 'EPSG:3857',
                    tileGrid: new ol.tilegrid.TileGrid({
                        resolutions: resolutions,
                        origin: [20037508.34,-20037508.34] })
                }),
                name: 'Tile Grid'
            });
            //layersArray.push(tileGrid);
            console.log(tileGrid);

            $.each( addLayersClientParams.referenceLayers, function ( idx, referenceLayer )
            {
                var osmGroup = new ol.layer.Tile( {
                    opacity: 1.0,
                    source: new ol.source.TileWMS( {
                        url: referenceLayer.url,
                        params: {'LAYERS': referenceLayer.name, 'TILED': true}
                    } ),
                    name: referenceLayer.title
                } );

                layersArray.push( osmGroup );

            } );

            $.each( addLayersClientParams.tileCacheLayers, function ( idx, tileCacheLayer )
            {
                var highres_3857 = new ol.layer.Tile( {
                    opacity: 1.0,
                    source: new ol.source.TileWMS( {
                        url: addLayersClientParams.accumuloProxyWmsURL,
                        params: {'LAYERS': tileCacheLayer.name, 'TILED': true, 'VERSION': '1.1.1'}
                    } ),
                    name: tileCacheLayer.name
                } );

                //layersArray.push( highres_3857 ); //highres_us
            } );

            $.each( addLayersClientParams.overlayLayers, function ( idx, overlayLayer )
            {
                var osmOverlay = new ol.layer.Tile( {
                    opacity: 1.0,
                    //visible: false,
                    source: new ol.source.TileWMS( {
                        url: overlayLayer.url,
                        params: {'LAYERS': overlayLayer.name, 'TILED': true}
                    } ),
                    name: overlayLayer.title
                } );

                layersArray.push( osmOverlay );

            } );

            layersArray.push(tileGrid);

        },
        layersArray: layersArray
    };
})();

<commit_msg>Fixed a origin for the grid.<commit_after>AddLayerClient = (function ()
{
    //var url ='http://10.0.10.184:8080/tilecache/accumuloProxy/wfs?request=GetFeature&typeName=tilecache:layers'
    //var url = "../json_3857.txt"; // For testing while not on RBT network
    var wfsURL;
    var layersArray = [];

    // This allows the client to request more tiles
    var tileUrls = [
        'http://s1:8080/tilecache/accumuloProxy/wms?',
        'http://s2:8080/tilecache/accumuloProxy/wms?',
        'http://s3:8080/tilecache/accumuloProxy/wms?',
        'http://s4:8080/tilecache/accumuloProxy/wms?'
    ];

    return {
        initialize: function ( addLayersClientParams )
        {
            wfsURL = addLayersClientParams.wfsURL;

            //var osmAwsAerialGroup = new ol.layer.Group( {
            //    layers: [
            //        new ol.layer.Tile( {
            //            style: 'Aerial',
            //            //visible: false,
            //            source: new ol.source.MapQuest( {layer: 'sat'} ),
            //            name: 'Aerial'
            //        } ),
            //        new ol.layer.Tile( {
            //            opacity: 1.0,
            //            source: new ol.source.TileWMS( {
            //                url: 'http://52.0.52.104/geoserver/ged/wms?',
            //                params: {'LAYERS': 'planet_osm_line', 'TILED': true}
            //            } ),
            //            name: 'Labels'
            //        } ),
            //        new ol.layer.Tile( {
            //            opacity: 1.0,
            //            source: new ol.source.TileWMS( {
            //                url: 'http://52.0.52.104/geoserver/ged/wms?',
            //                params: {'LAYERS': 'ne_10m_populated_places_all', 'TILED': true}
            //            } ),
            //            name: 'Place Names'
            //        } )
            //    ],
            //    name: 'Aerial and Labels'
            //} );

            var tileBoundsVectorSource = new ol.source.GeoJSON( {
                url: wfsURL,
                crossOrigin: 'anonymous',
                projection: 'EPSG:3857'
            } );

            // Tile sets extents layer
            //var tileBoundsVectorLayer = new ol.layer.Vector( {
            //    source: tileBoundsVectorSource,
            //    style: (function ()
            //    {
            //        var stroke = new ol.style.Stroke( {
            //            color: 'red',
            //            width: 5
            //        } );
            //        var textStroke = new ol.style.Stroke( {
            //            color: '#fff',
            //            width: 3
            //        } );
            //        var textFill = new ol.style.Fill( {
            //            color: 'red'
            //        } );
            //        return function ( feature, resolution )
            //        {
            //            return [new ol.style.Style( {
            //                stroke: stroke,
            //                text: new ol.style.Text( {
            //                    font: '36px Calibri,sans-serif',
            //                    text: 'Name: ' + feature.get( 'name' ) + ' Min: ' + feature.get( 'min_level' ) + ' Max: ' + feature.get( 'max_level' ),
            //                    fill: textFill,
            //                    stroke: textStroke
            //                } )
            //            } )];
            //        };
            //    })(),
            //    name: 'Tile Set Boundaries'
            //} );

            var resolutions = [
                156543.03392804097,
                78271.51696402048,
                39135.75848201024,
                19567.87924100512,
                9783.93962050256,
                4891.96981025128,
                2445.98490512564,
                1222.99245256282,
                611.49622628141,
                305.748113140705,
                152.8740565703525,
                76.43702828517625,
                38.21851414258813,
                19.109257071294063,
                9.554628535647032,
                4.777314267823516,
                2.388657133911758,
                1.194328566955879,
                0.5971642834779395,
                0.29858214173896974
            ];

            var tileGrid = new ol.layer.Tile({
                source: new ol.source.TileDebug({
                    projection: 'EPSG:3857',
                    tileGrid: new ol.tilegrid.TileGrid({
                        resolutions: resolutions,
                        origin: [-20037508.342789244, 20037508.342789244] })
                }),
                name: 'Tile Grid'
            });
            //layersArray.push(tileGrid);
            console.log(tileGrid);

            $.each( addLayersClientParams.referenceLayers, function ( idx, referenceLayer )
            {
                var osmGroup = new ol.layer.Tile( {
                    opacity: 1.0,
                    source: new ol.source.TileWMS( {
                        url: referenceLayer.url,
                        params: {'LAYERS': referenceLayer.name, 'TILED': true}
                    } ),
                    name: referenceLayer.title
                } );

                layersArray.push( osmGroup );

            } );

            $.each( addLayersClientParams.tileCacheLayers, function ( idx, tileCacheLayer )
            {
                var highres_3857 = new ol.layer.Tile( {
                    opacity: 1.0,
                    source: new ol.source.TileWMS( {
                        url: addLayersClientParams.accumuloProxyWmsURL,
                        params: {'LAYERS': tileCacheLayer.name, 'TILED': true, 'VERSION': '1.1.1'}
                    } ),
                    name: tileCacheLayer.name
                } );

                layersArray.push( highres_3857 ); //highres_us
            } );

            $.each( addLayersClientParams.overlayLayers, function ( idx, overlayLayer )
            {
                var osmOverlay = new ol.layer.Tile( {
                    opacity: 1.0,
                    //visible: false,
                    source: new ol.source.TileWMS( {
                        url: overlayLayer.url,
                        params: {'LAYERS': overlayLayer.name, 'TILED': true}
                    } ),
                    name: overlayLayer.title
                } );

                layersArray.push( osmOverlay );

            } );

            layersArray.push(tileGrid);

        },
        layersArray: layersArray
    };
})();

<|endoftext|>


<commit_before>(function($){

  $.fn.extend({
    datetimeparse: function(options) {

      var defaults = {
        //something like this: defaultTime: 08:00:00
      }

      var options =  $.extend(defaults, options);

      return this.each(function() {
        var inputText = $.trim($(this).val()); //no harm...
        console.log("Got input: "+inputText);
        console.log("Is date? "+isDate(inputText));
        var parsedDate = new Date();
        return parsedDate;
      });

      function on(time, date){
        //on is called when something like this is found: 7 PM on Friday
        return;
      }
      function at(date, time) {
        //at is called when something like this is found: Friday at 7 PM
        return;
      }
      function isDate(date) {
        //second or third character needs to be a slash.
        date = $.trim(date);
        if (date.length <= 5) {
          //No year specified, so only one slash...
          //Check length because otherwise things like "1/" are valid...
          return ( (date.charAt(1) == '/' && date.length > 2) || (date.charAt(2) == '/' && date.length > 3) );
        }
        else {
          //If we're here... Date must include year, so check for two slashes.
          var firstSlash = (date.charAt(1) == '/' || date.charAt(2) == '/');
          var secondSlash = (date.charAt(3) == '/' || date.charAt(4) == '/' || date.charAt(5) == '/');
          return (firstSlash && secondSlash && date.charAt(-1) != '/');
        }
      }
      function dateInFuture(date) {
        var now = new Date();
        if (date > now) {return true;}
        return false;
      }
    }

  });

})(jQuery);<commit_msg>Added dayOfTheWeek function. Refactored isDate a little, checking last char is / instead of length.<commit_after>(function($){

  $.fn.extend({
    datetimeparse: function(options) {

      var defaults = {
        //Option for assuming future set to true or false...
      }

      var options =  $.extend(defaults, options);

      return this.each(function() {
        var inputText = $.trim($(this).val()); //no harm...
        console.log("Got input: "+inputText);
        console.log("Is date? "+isDate(inputText));
        var parsedDate = today();
        console.log("Is DOTW? "+dayOfTheWeek(inputText));
        console.log(parsedDate);
      });
      return parsedDate;
      function today() {
        retVal = new Date();
        retVal.setHours(0); //Midnight
        retVal.setMinutes(0);
        retVal.setSeconds(0);
        retVal.setMilliseconds(0);
        return retVal;
      }
      function on(time, date) {
        //on is called when something like this is found: 7 PM on Friday
        return;
      }
      function at(date, time) {
        //at is called when something like this is found: Friday at 7 PM
        return;
      }
      function isDate(date) {
        //second or third character needs to be a slash.
        date = $.trim(date);
        if (date.substr(-1) == '/') {return false;} //Last char is a slash it is not complete yet...
        if (date.length <= 5) {
          //No year specified, so only one slash...
          return ( date.charAt(1) == '/' || date.charAt(2) == '/' );
        }
        else {
          //If we're here... Date must include year, so check for two slashes.
          var firstSlash = (date.charAt(1) == '/' || date.charAt(2) == '/');
          var secondSlash = (date.charAt(3) == '/' || date.charAt(4) == '/' || date.charAt(5) == '/');
          return (firstSlash && secondSlash);
        }
      }
      function dayOfTheWeek(dotw) {
        switch(dotw.toLowerCase()) {
          case "mon": case "monday":
            var day = 0;
            break;
          case "tue": case "tues": case "tuesday":
            var day = 1;
            break;
          case "wed": case "wednesday":
            var day = 2;
            break;
          case "thur": case "thurs": case "thursday":
            var day = 3;
            break;
          case "fri": case "friday":
            var day = 4;
            break;
          case "sat": case "saturday":
            var day = 5;
            break;
          case "sun": case "sunday":
            var day = 6;
            break;
        }
        if (day != undefined)
        {
          return day;
        }
        return false;
      }
      function dateInFuture(date) {
        var now = new Date();
        if (date > now) {return true;}
        return false;
      }
    }

  });

})(jQuery);<|endoftext|>


<commit_before>(function($){

  $.fn.extend({
    datetimeparse: function(options) {

      var defaults = {
        //Option for assuming future set to true or false...
        hours: 0,
        minutes: 0,
        seconds: 0,
        milliseconds: 0
      }

      var options =  $.extend(defaults, options);
      var parsedDate;
      this.each(function() {
        var inputText = $.trim($(this).val()); //no harm...
        console.log("Got input: "+inputText);
        console.log("Is date? "+isDate(inputText));
        parsedDate = today();
        console.log("Is DOTW? "+dayOfTheWeek(inputText));
        console.log(parsedDate);
      });
      if (parsedDate == undefined) {
        return "Something went wrong!";
      }
      return parsedDate;
      function defaultTime(oldDate) {
        oldDate = typeof(oldDate) != 'undefined' ? oldDate : new Date();
        oldDate.setHours(options.hours);
        oldDate.setMinutes(options.minutes);
        oldDate.setSeconds(options.seconds);
        oldDate.setMilliseconds(options.milliseconds);
        return oldDate;
      }
      function on(time, date) {
        //on is called when something like this is found: 7 PM on Friday
        return;
      }
      function at(date, time) {
        //at is called when something like this is found: Friday at 7 PM
        return;
      }
      function isDate(date) {
        //second or third character needs to be a slash.
        date = $.trim(date);
        if (date.substr(-1) == '/') {return false;} //If last char is a slash it is not complete yet...
        if (date.length <= 5) {
          //No year specified, so only one slash...
          return ( date.charAt(1) == '/' || date.charAt(2) == '/' );
        }
        else {
          //If we're here... Date must include year, so check for two slashes.
          //Year is either two or four chars...
          var year = date.split('/').pop();
          if (year.length != 2 && year.length != 4) {return false;}

          var firstSlash = (date.charAt(1) == '/' || date.charAt(2) == '/');
          var secondSlash = (date.charAt(3) == '/' || date.charAt(4) == '/' || date.charAt(5) == '/');
          return (firstSlash && secondSlash);
        }
      }
      function isPeriod(period) {
        var retval = false;
        switch(period) {
          case "a": case "am":
            retval = true;
            break;
          case "p": case "pm":
            retval = true;
            break;
        }
        return retval;
      }
      function isTime(time) {
        //TIME = [H, H:MM, HH:MM]
        timeComponents = time.split(':');
        if (time.length < 2 && timeComponents.length == 1) {return true;}
        timeArray = time.split(':');
        if (timeArray.length == 2) {return true;}
        return false;

      }
      function dayOfTheWeek(dotw) {
        switch(dotw.toLowerCase()) {
          case "mon": case "monday":
            var day = 0;
            break;
          case "tue": case "tues": case "tuesday":
            var day = 1;
            break;
          case "wed": case "wednesday":
            var day = 2;
            break;
          case "thur": case "thurs": case "thursday":
            var day = 3;
            break;
          case "fri": case "friday":
            var day = 4;
            break;
          case "sat": case "saturday":
            var day = 5;
            break;
          case "sun": case "sunday":
            var day = 6;
            break;
        }
        if (day != undefined)
        {
          return day;
        }
        return false;
      }
      function dateInFuture(date) {
        var now = new Date();
        if (date > now) {return true;}
        return false;
      }
    }

  });

})(jQuery);<commit_msg>Added getInputTime and getInputHour functions.<commit_after>(function($){

  $.fn.extend({
    datetimeparse: function(options) {

      var defaults = {
        //Option for assuming future set to true or false...
        hours: 0,
        minutes: 0,
        seconds: 0,
        milliseconds: 0
      }

      var options =  $.extend(defaults, options);
      var parsedDate;
      this.each(function() {
        var inputText = $.trim($(this).val()); //no harm...
        console.log("Got input: "+inputText);
        console.log("Is date? "+isDate(inputText));
        parsedDate = today();
        console.log("Is DOTW? "+dayOfTheWeek(inputText));
        console.log(parsedDate);
      });
      if (parsedDate == undefined) {
        return "Something went wrong!";
      }
      return parsedDate;
      function getInputMinute(time) {
        timeArray = time.split(':');
        if (timeArray.length < 2) {return 0;}
        return timeArray.pop();
      }
      function getInputHour(time,period) {
        if (period.indexOf('a') != -1) {
          //am... so make sure hours < 11 (11 == 12 PM in setHours)
          timeArray = time.split(':');
          var hour = timeArray.shift();
          if (hour > 11) {
            return hour - 12;
          }
          return hour;
        }
      }
      function defaultTime(oldDate) {
        oldDate = typeof(oldDate) != 'undefined' ? oldDate : new Date();
        oldDate.setHours(options.hours);
        oldDate.setMinutes(options.minutes);
        oldDate.setSeconds(options.seconds);
        oldDate.setMilliseconds(options.milliseconds);
        return oldDate;
      }
      function on(time, date) {
        //on is called when something like this is found: 7 PM on Friday
        return;
      }
      function at(date, time) {
        //at is called when something like this is found: Friday at 7 PM
        return;
      }
      function isDate(date) {
        //second or third character needs to be a slash.
        date = $.trim(date);
        if (date.substr(-1) == '/') {return false;} //If last char is a slash it is not complete yet...
        if (date.length <= 5) {
          //No year specified, so only one slash...
          return ( date.charAt(1) == '/' || date.charAt(2) == '/' );
        }
        else {
          //If we're here... Date must include year, so check for two slashes.
          //Year is either two or four chars...
          var year = date.split('/').pop();
          if (year.length != 2 && year.length != 4) {return false;}

          var firstSlash = (date.charAt(1) == '/' || date.charAt(2) == '/');
          var secondSlash = (date.charAt(3) == '/' || date.charAt(4) == '/' || date.charAt(5) == '/');
          return (firstSlash && secondSlash);
        }
      }
      function isPeriod(period) {
        var retval = false;
        switch(period) {
          case "a": case "am":
            retval = true;
            break;
          case "p": case "pm":
            retval = true;
            break;
        }
        return retval;
      }
      function isTime(time) {
        //TIME = [H, H:MM, HH:MM]
        timeComponents = time.split(':');
        if (time.length < 2 && timeComponents.length == 1) {return true;}
        timeArray = time.split(':');
        if (timeArray.length == 2) {return true;}
        return false;

      }
      function dayOfTheWeek(dotw) {
        switch(dotw.toLowerCase()) {
          case "mon": case "monday":
            var day = 0;
            break;
          case "tue": case "tues": case "tuesday":
            var day = 1;
            break;
          case "wed": case "wednesday":
            var day = 2;
            break;
          case "thur": case "thurs": case "thursday":
            var day = 3;
            break;
          case "fri": case "friday":
            var day = 4;
            break;
          case "sat": case "saturday":
            var day = 5;
            break;
          case "sun": case "sunday":
            var day = 6;
            break;
        }
        if (day != undefined)
        {
          return day;
        }
        return false;
      }
      function dateInFuture(date) {
        var now = new Date();
        if (date > now) {return true;}
        return false;
      }
    }

  });

})(jQuery);<|endoftext|>


<commit_before>// jquery.observe_field.js

(function( $ ){

  jQuery.fn.observe_field = function(frequency, callback) {

    frequency = frequency * 1000; // translate to milliseconds

    return this.each(function(){
      var $this = $(this);
      var prev = $this.val();

      var check = function() {
        var val = $this.val();
        if(prev != val){
          prev = val;
          $this.map(callback); // invokes the callback on $this
        }
      };

      var reset = function() {
        if(ti){
          clearInterval(ti);
          ti = setInterval(check, frequency);
        }
      };

      check();
      var ti = setInterval(check, frequency); // invoke check periodically

      // reset counter after user interaction
      $this.bind('keyup mousemove', reset); //mousemove is for selects
    });

  };

})( jQuery );

<commit_msg>click now also resets the counter<commit_after>// jquery.observe_field.js

(function( $ ){

  jQuery.fn.observe_field = function(frequency, callback) {

    frequency = frequency * 1000; // translate to milliseconds

    return this.each(function(){
      var $this = $(this);
      var prev = $this.val();

      var check = function() {
        var val = $this.val();
        if(prev != val){
          prev = val;
          $this.map(callback); // invokes the callback on $this
        }
      };

      var reset = function() {
        if(ti){
          clearInterval(ti);
          ti = setInterval(check, frequency);
        }
      };

      check();
      var ti = setInterval(check, frequency); // invoke check periodically

      // reset counter after user interaction
      $this.bind('keyup click mousemove', reset); //mousemove is for selects
    });

  };

})( jQuery );

<|endoftext|>


<commit_before>
/*
d3.select("#nav-bar").html(`

	  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
	    Toggle navigation

	  </button>
	  Personal Polynomial
	  Make PDF

`
	);
*/

d3.select("#fb-div").on("click",
	d3.select("#fb-description").style({property="og:description"   content="Did this work?"})
	);

//d3.select("#fb-image")<commit_msg>fb test<commit_after>
/*
d3.select("#nav-bar").html(`

	  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
	    Toggle navigation

	  </button>
	  Personal Polynomial
	  Make PDF

`
	);
*/

d3.select("#fb-div").on("click",
	d3.select("#fb-description").property({property="og:description"   content="Did this work?"})
	);

//d3.select("#fb-image")<|endoftext|>


<commit_before>/*
 * waitForImages 1.3.1
 * -----------------
 * Provides a callback when all images have loaded in your given selector.
 * http://www.alexanderdickson.com/
 *
 *
 * Copyright (c) 2011 Alex Dickson
 * Licensed under the MIT licenses.
 * See website for more info.
 *
 */

;(function($) {

    // CSS properties which contain references to images.
    $.waitForImages = {
        hasImageProperties: [
        'backgroundImage',
        'listStyleImage',
        'borderImage',
        'borderCornerImage'
        ]
    };

    // Custom selector to find `img` elements that have a valid `src` attribute and have not already loaded.
    $.expr[':'].uncached = function(obj) {
        return $(obj).is('img[src!=""]') && ! obj.complete;
    };

    $.fn.waitForImages = function(finishedCallback, eachCallback, waitForAll) {

        // Handle options object.
        if ($.type(arguments[0]) == 'object') {
            eachCallback = finishedCallback.each;
            waitForAll = finishedCallback.waitForAll;
            finishedCallback = finishedCallback.finished;
        }

        // Handle missing callbacks.
        finishedCallback = finishedCallback || function() {};
        eachCallback = eachCallback || function() {};

        // Convert waitForAll to Boolean
        waitForAll = !! waitForAll;

        // Ensure callbacks are functions.
        if (!$.isFunction(finishedCallback) || !$.isFunction(eachCallback)) {
            throw new TypeError('An invalid callback was supplied.');
        };

        return this.each(function() {
            // Build a list of all imgs, dependent on what images will be considered.
            var obj = $(this),
                allImgs = [];

            if (waitForAll) {
                // CSS properties which may contain an image.
                var hasImgProperties = $.waitForImages.hasImageProperties,
                    matchUrl = /url\((['"]?)(.*?)\1\)/g;

                // Get all elements, as any one of them could have a background image.
                obj.find('*').each(function() {
                    var element = $(this);

                    // If an `img` element, add it. But keep iterating in case it has a background image too.
                    if (element.is('img:uncached')) {
                        allImgs.push({
                            src: element.attr('src'),
                            element: element[0]
                        });
                    }

                    $.each(hasImgProperties, function(i, property) {
                        var propertyValue = element.css(property);
                        // If it doesn't contain this property, skip.
                        if ( ! propertyValue) {
                            return true;
                        }

                        // Get all url() of this element.
                        var match;
                        while (match = matchUrl.exec(propertyValue)) {
                            allImgs.push({
                                src: match[2],
                                element: element[0]
                            });
                        };
                    });
                });
            } else {
                // For images only, the task is simpler.
                obj
                 .find('img:uncached')
                 .each(function() {
                    allImgs.push({
                        src: this.src,
                        element: this
                    });
                });
            };

            var allImgsLength = allImgs.length,
                allImgsLoaded = 0;

            // If no images found, don't bother.
            if (allImgsLength == 0) {
                finishedCallback.call(obj[0]);
            };

            $.each(allImgs, function(i, img) {

                var image = new Image;

                // Handle the image loading and error with the same callback.
                $(image).bind('load error', function(event) {
                    allImgsLoaded++;

                    // If an error occurred with loading the image, set the third argument accordingly.
                    eachCallback.call(img.element, allImgsLoaded, allImgsLength, event.type == 'load');

                    if (allImgsLoaded == allImgsLength) {
                        finishedCallback.call(obj[0]);
                        return false;
                    };

                });

                image.src = img.src;
            });
        });
    };
})(jQuery);
<commit_msg>Changed argument object checking and provided array literal fallback for  array.<commit_after>/*
 * waitForImages 1.3.1
 * -----------------
 * Provides a callback when all images have loaded in your given selector.
 * http://www.alexanderdickson.com/
 *
 *
 * Copyright (c) 2011 Alex Dickson
 * Licensed under the MIT licenses.
 * See website for more info.
 *
 */

;(function($) {

    // CSS properties which contain references to images.
    $.waitForImages = {
        hasImageProperties: [
        'backgroundImage',
        'listStyleImage',
        'borderImage',
        'borderCornerImage'
        ]
    };

    // Custom selector to find `img` elements that have a valid `src` attribute and have not already loaded.
    $.expr[':'].uncached = function(obj) {
        return $(obj).is('img[src!=""]') && ! obj.complete;
    };

    $.fn.waitForImages = function(finishedCallback, eachCallback, waitForAll) {

        // Handle options object.
        if ($.isPlainObject(arguments[0])) {
            eachCallback = finishedCallback.each;
            waitForAll = finishedCallback.waitForAll;
            finishedCallback = finishedCallback.finished;
        }

        // Handle missing callbacks.
        finishedCallback = finishedCallback || function() {};
        eachCallback = eachCallback || function() {};

        // Convert waitForAll to Boolean
        waitForAll = !! waitForAll;

        // Ensure callbacks are functions.
        if (!$.isFunction(finishedCallback) || !$.isFunction(eachCallback)) {
            throw new TypeError('An invalid callback was supplied.');
        };

        return this.each(function() {
            // Build a list of all imgs, dependent on what images will be considered.
            var obj = $(this),
                allImgs = [];

            if (waitForAll) {
                // CSS properties which may contain an image.
                var hasImgProperties = $.waitForImages.hasImageProperties || [],
                    matchUrl = /url\((['"]?)(.*?)\1\)/g;

                // Get all elements, as any one of them could have a background image.
                obj.find('*').each(function() {
                    var element = $(this);

                    // If an `img` element, add it. But keep iterating in case it has a background image too.
                    if (element.is('img:uncached')) {
                        allImgs.push({
                            src: element.attr('src'),
                            element: element[0]
                        });
                    }

                    $.each(hasImgProperties, function(i, property) {
                        var propertyValue = element.css(property);
                        // If it doesn't contain this property, skip.
                        if ( ! propertyValue) {
                            return true;
                        }

                        // Get all url() of this element.
                        var match;
                        while (match = matchUrl.exec(propertyValue)) {
                            allImgs.push({
                                src: match[2],
                                element: element[0]
                            });
                        };
                    });
                });
            } else {
                // For images only, the task is simpler.
                obj
                 .find('img:uncached')
                 .each(function() {
                    allImgs.push({
                        src: this.src,
                        element: this
                    });
                });
            };

            var allImgsLength = allImgs.length,
                allImgsLoaded = 0;

            // If no images found, don't bother.
            if (allImgsLength == 0) {
                finishedCallback.call(obj[0]);
            };

            $.each(allImgs, function(i, img) {

                var image = new Image;

                // Handle the image loading and error with the same callback.
                $(image).bind('load error', function(event) {
                    allImgsLoaded++;

                    // If an error occurred with loading the image, set the third argument accordingly.
                    eachCallback.call(img.element, allImgsLoaded, allImgsLength, event.type == 'load');

                    if (allImgsLoaded == allImgsLength) {
                        finishedCallback.call(obj[0]);
                        return false;
                    };

                });

                image.src = img.src;
            });
        });
    };
})(jQuery);
<|endoftext|>


<commit_before><commit_msg>add 403 error handler<commit_after><|endoftext|>


<commit_before>/**
 * cbpAnimatedHeader.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2013, Codrops
 * http://www.codrops.com
 */
var cbpAnimatedHeader = (function() {

	var docElem = document.documentElement,
		header = document.querySelector( '.navbar-default' ),
		didScroll = false,
		changeHeaderOn = 300;

	function init() {
		window.addEventListener( 'scroll', function( event ) {
			if( !didScroll ) {
				didScroll = true;
				setTimeout( scrollPage, 250 );
			}
		}, false );
	}

	function scrollPage() {
		var sy = scrollY();
		if ( sy >= changeHeaderOn ) {
			classie.add( header, 'navbar-shrink' );
		}
		else {
			classie.remove( header, 'navbar-shrink' );
		}
		didScroll = false;
	}

	function scrollY() {
		return window.pageYOffset || docElem.scrollTop;
	}

	init();

})();<commit_msg>testing alert<commit_after>/**
 * cbpAnimatedHeader.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2013, Codrops
 * http://www.codrops.com
 */
var cbpAnimatedHeader = (function () {

    alert("made it to animated header");

	var docElem = document.documentElement,
		header = document.querySelector( '.navbar-default' ),
		didScroll = false,
		changeHeaderOn = 300;

	function init() {
		window.addEventListener( 'scroll', function( event ) {
			if( !didScroll ) {
				didScroll = true;
				setTimeout( scrollPage, 250 );
			}
		}, false );
	}

	function scrollPage() {
		var sy = scrollY();
		if ( sy >= changeHeaderOn ) {
			classie.add( header, 'navbar-shrink' );
		}
		else {
			classie.remove( header, 'navbar-shrink' );
		}
		didScroll = false;
	}

	function scrollY() {
		return window.pageYOffset || docElem.scrollTop;
	}

	init();

})();<|endoftext|>


<commit_before>var game = new Phaser.Game(900, 500, Phaser.CANVAS, 'center', {
    preload: construtor,
    create: construiu,
    update: animacao
});

var app = {};

function construtor() {
    game.load.image('fundo', 'img/bomba/back.jpg');
    game.load.image('terra', 'img/bomba/fundo.png')
    game.load.image('canhao', 'img/bomba/canhao1.png');
    game.load.image('dog', 'img/bomba/cachorro.png');
    game.load.image('homem', 'img/bomba/homem.png');

    app.forca = 0;
    app.angulo = 0;
    app.exec = true; //verificar se esta executando o play
}

function construiu() {
    game.world.setBounds(0, 0, 2000, 500); // seta tamanho da colisão da tela

    //adiciona as imagens na ela
    adicionandoImagens();

    //setando tipo de fisica
    game.physics.startSystem(Phaser.Physics.P2JS);
    //efeito pingar mais forte
    game.physics.p2.restitution = 0.0;
    game.physics.p2.gravity.y = 800;

    //adicionando fisica
    // game.physics.p2.enable(app.terra, true);
    game.physics.p2.enable(app.canhao, false);
    game.physics.p2.enable(app.dog, false);
    game.physics.p2.enable(app.homem, false);

    //seta valor statico canhão
    //iria fazer eles se movimentando
    //de acordo com o angulo mas desisti
    app.canhao.body.x = 80;
    app.canhao.body.y = 420;
    app.canhao.body.setZeroVelocity();
    app.canhao.body.fixedRotation = true;
    app.canhao.body.collideWorldBounds = false;

    //setando valores staticos do cachorro
    app.dog.body.x = gerarValoresRandomicos(150, 1990);
    app.dog.body.setZeroVelocity();
    app.dog.body.fixedRotation = true;

    //setando valores staticos do homem
    zerarHomem(); // volta todos os valores para os iniciais

    app.homem.body.createBodyCallback(app.dog, colidirDog, this); //evento de toque do homem ao cachorro
    game.physics.p2.setImpactEvents(true); //habilita o callback para eventos de colião

    app.cursor = game.input.keyboard.createCursorKeys(); // pega as keys digitadas

    app.um = game.input.keyboard.addKey(Phaser.Keyboard.ONE); // adiciona o envento para botao 1
    app.um.onDown.add(callUm, this);

    app.dois = game.input.keyboard.addKey(Phaser.Keyboard.TWO); // adiciona o envento para botao 2
    app.dois.onDown.add(callDois, this);

    app.go = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); // adiciona o envento para botao espaço
    app.go.onDown.add(execHomem, this);

    app.exec = true; // evita que de para dar duplo espaço no executar

    //adiciona texto legenda
    app.texto = game.add.text(30, 10, 'Alterar Força: 1/2 - Alterar Angulo: Up/Down - Lançar o Rafa - Espaço - Direcionar camera - left/right', {
        font: "12px sans-serif",
        fill: "#ffffff",
        align: "center"
    });
    inserirTextoForca(); //insere texto de forca e angulo
    inserirTextoAngulo();

}

function animacao() {
    app.canhao.body.setZeroVelocity();
    app.canhao.body.x = 80;
    app.canhao.body.y = 420;

    //verifica se tocou no chão antes de tocar no dog
    if (parseInt(app.homem.body.y, 10) == 428) {
        zerarHomem();
    }

    app.dog.body.setZeroVelocity();

    app.homem.body.angle = 35;

    if (!app.homem.acao) {
        app.homem.body.setZeroVelocity();
        app.homem.body.y = 390;
    }

    execControles();

}

function adicionandoImagens() {

    //adicionando fundo
    app.fundo = game.add.image(0, 0, 'fundo');

    app.terra = game.add.tileSprite(0, 404, 2000, 96, 'terra');

    app.homem = game.add.sprite(120, 390, 'homem');

    app.canhao = game.add.sprite(0, 0, 'canhao');

    app.dog = game.add.sprite(800, 450, 'dog');

}

function execControles() {
    if (app.cursor.up.isDown) {
        app.angulo += 50;
        console.log('Angulo: ' + app.angulo);
        inserirTextoAngulo();
    } else if (app.cursor.down.isDown) {
        app.angulo -= 50;
        console.log('Angulo: ' + app.angulo);
        inserirTextoAngulo();
    }

    if (app.cursor.left.isDown) {
        game.camera.x -= 4;
    } else if (app.cursor.right.isDown) {
        game.camera.x += 4;
    }

}

function callUm() {
    app.forca += 50;
    console.log('Força: ' + app.forca);
    inserirTextoForca();
}

function callDois() {
    app.forca -= 50;
    console.log('Força: ' + app.forca);
    inserirTextoForca();
}

function zerarHomem() {
    app.homem.body.angle = 35;
    app.homem.body.setRectangle(80, 120);
    app.homem.body.fixedRotation = true;
    app.homem.body.x = 120;
    app.homem.body.y = 390;
    app.homem.acao = false;
    app.exec = true;
    game.camera.unfollow();
    game.camera.x = 0;
}

function execHomem() {
    if (app.exec) {
        game.camera.follow(app.homem);
        app.homem.acao = true;
        app.homem.body.velocity.x = app.forca;
        app.homem.body.velocity.y = (app.angulo * -1);
        app.exec = false;
    }
}

function colidirDog() {
    alert('Encontrou!');
    app.dog.body.x = gerarValoresRandomicos(150, 1990);
    zerarHomem();
}

function inserirTextoForca() {

    var montarTexto = 'Força: ' + app.forca;

    if (app.texto.forca) {
        app.texto.forca.text = montarTexto;
    } else {
        var style = {
            font: "12px sans-serif",
            fill: "#ffffff",
            align: "center"
        };
        app.texto.forca = game.add.text(30, 30, montarTexto, style);
    }
}

function inserirTextoAngulo() {

    var montarTexto = 'Angulo: ' + app.angulo;

    if (app.texto.angulo) {
        app.texto.angulo.text = montarTexto;
    } else {
        var style = {
            font: "12px sans-serif",
            fill: "#ffffff",
            align: "center"
        };
        app.texto.angulo = game.add.text(30, 50, montarTexto, style);
    }
}

function gerarValoresRandomicos(min, max) {
    return Math.random() * (max - min) + min;
}<commit_msg>ajustado velocidade camera<commit_after>var game = new Phaser.Game(900, 500, Phaser.CANVAS, 'center', {
    preload: construtor,
    create: construiu,
    update: animacao
});

var app = {};

function construtor() {
    game.load.image('fundo', 'img/bomba/back.jpg');
    game.load.image('terra', 'img/bomba/fundo.png')
    game.load.image('canhao', 'img/bomba/canhao1.png');
    game.load.image('dog', 'img/bomba/cachorro.png');
    game.load.image('homem', 'img/bomba/homem.png');

    app.forca = 0;
    app.angulo = 0;
    app.exec = true; //verificar se esta executando o play
}

function construiu() {
    game.world.setBounds(0, 0, 2000, 500); // seta tamanho da colisão da tela

    //adiciona as imagens na ela
    adicionandoImagens();

    //setando tipo de fisica
    game.physics.startSystem(Phaser.Physics.P2JS);
    //efeito pingar mais forte
    game.physics.p2.restitution = 0.0;
    game.physics.p2.gravity.y = 800;

    //adicionando fisica
    // game.physics.p2.enable(app.terra, true);
    game.physics.p2.enable(app.canhao, false);
    game.physics.p2.enable(app.dog, false);
    game.physics.p2.enable(app.homem, false);

    //seta valor statico canhão
    //iria fazer eles se movimentando
    //de acordo com o angulo mas desisti
    app.canhao.body.x = 80;
    app.canhao.body.y = 420;
    app.canhao.body.setZeroVelocity();
    app.canhao.body.fixedRotation = true;
    app.canhao.body.collideWorldBounds = false;

    //setando valores staticos do cachorro
    app.dog.body.x = gerarValoresRandomicos(150, 1990);
    app.dog.body.setZeroVelocity();
    app.dog.body.fixedRotation = true;

    //setando valores staticos do homem
    zerarHomem(); // volta todos os valores para os iniciais

    app.homem.body.createBodyCallback(app.dog, colidirDog, this); //evento de toque do homem ao cachorro
    game.physics.p2.setImpactEvents(true); //habilita o callback para eventos de colião

    app.cursor = game.input.keyboard.createCursorKeys(); // pega as keys digitadas

    app.um = game.input.keyboard.addKey(Phaser.Keyboard.ONE); // adiciona o envento para botao 1
    app.um.onDown.add(callUm, this);

    app.dois = game.input.keyboard.addKey(Phaser.Keyboard.TWO); // adiciona o envento para botao 2
    app.dois.onDown.add(callDois, this);

    app.go = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); // adiciona o envento para botao espaço
    app.go.onDown.add(execHomem, this);

    app.exec = true; // evita que de para dar duplo espaço no executar

    //adiciona texto legenda
    app.texto = game.add.text(30, 10, 'Alterar Força: 1/2 - Alterar Angulo: Up/Down - Lançar o Rafa - Espaço - Direcionar camera - left/right', {
        font: "12px sans-serif",
        fill: "#ffffff",
        align: "center"
    });
    inserirTextoForca(); //insere texto de forca e angulo
    inserirTextoAngulo();

}

function animacao() {
    app.canhao.body.setZeroVelocity();
    app.canhao.body.x = 80;
    app.canhao.body.y = 420;

    //verifica se tocou no chão antes de tocar no dog
    if (parseInt(app.homem.body.y, 10) == 428) {
        zerarHomem();
    }

    app.dog.body.setZeroVelocity();

    app.homem.body.angle = 35;

    if (!app.homem.acao) {
        app.homem.body.setZeroVelocity();
        app.homem.body.y = 390;
    }

    execControles();

}

function adicionandoImagens() {

    //adicionando fundo
    app.fundo = game.add.image(0, 0, 'fundo');

    app.terra = game.add.tileSprite(0, 404, 2000, 96, 'terra');

    app.homem = game.add.sprite(120, 390, 'homem');

    app.canhao = game.add.sprite(0, 0, 'canhao');

    app.dog = game.add.sprite(800, 450, 'dog');

}

function execControles() {
    if (app.cursor.up.isDown) {
        app.angulo += 50;
        console.log('Angulo: ' + app.angulo);
        inserirTextoAngulo();
    } else if (app.cursor.down.isDown) {
        app.angulo -= 50;
        console.log('Angulo: ' + app.angulo);
        inserirTextoAngulo();
    }

    if (app.cursor.left.isDown) {
        game.camera.x -= 20;
    } else if (app.cursor.right.isDown) {
        game.camera.x += 20;
    }

}

function callUm() {
    app.forca += 50;
    console.log('Força: ' + app.forca);
    inserirTextoForca();
}

function callDois() {
    app.forca -= 50;
    console.log('Força: ' + app.forca);
    inserirTextoForca();
}

function zerarHomem() {
    app.homem.body.angle = 35;
    app.homem.body.setRectangle(80, 120);
    app.homem.body.fixedRotation = true;
    app.homem.body.x = 120;
    app.homem.body.y = 390;
    app.homem.acao = false;
    app.exec = true;
    game.camera.unfollow();
    game.camera.x = 0;
}

function execHomem() {
    if (app.exec) {
        game.camera.follow(app.homem);
        app.homem.acao = true;
        app.homem.body.velocity.x = app.forca;
        app.homem.body.velocity.y = (app.angulo * -1);
        app.exec = false;
    }
}

function colidirDog() {
    alert('Encontrou!');
    app.dog.body.x = gerarValoresRandomicos(150, 1990);
    zerarHomem();
}

function inserirTextoForca() {

    var montarTexto = 'Força: ' + app.forca;

    if (app.texto.forca) {
        app.texto.forca.text = montarTexto;
    } else {
        var style = {
            font: "12px sans-serif",
            fill: "#ffffff",
            align: "center"
        };
        app.texto.forca = game.add.text(30, 30, montarTexto, style);
    }
}

function inserirTextoAngulo() {

    var montarTexto = 'Angulo: ' + app.angulo;

    if (app.texto.angulo) {
        app.texto.angulo.text = montarTexto;
    } else {
        var style = {
            font: "12px sans-serif",
            fill: "#ffffff",
            align: "center"
        };
        app.texto.angulo = game.add.text(30, 50, montarTexto, style);
    }
}

function gerarValoresRandomicos(min, max) {
    return Math.random() * (max - min) + min;
}<|endoftext|>