<commit_before>/**
 * jQuery Stepy - A Wizard Plugin - http://wbotelhos.com/stepy
 * ---------------------------------------------------------------------------------
 *
 * jQuery Stepy is a plugin based on FormToWizard that generates a customizable wizard.
 *
 * Licensed under The MIT License
 *
 * @version			0.2.0
 * @since			07.03.2010
 * @author			Washington Botelho dos Santos
 * @documentation	http://wbotelhos.com/raty
 * @twitter			http://twitter.com/wbotelhos
 * @license			http://opensource.org/licenses/mit-license.php MIT
 * @package			jQuery Plugins
 *
 * Usage with default values:
 * ---------------------------------------------------------------------------------
 * $('#default').stepy();
 *
 *	<form id="default">
 *		<fieldset title="Step 1">
 *			<legend>description one</legend>
 *
 *		</fieldset>
 *
 *		<fieldset title="Step 2">
 *			<legend>description one</legend>
 *
 *		</fieldset>
 *
 *		// and so on..
 *
 *		<input type="submit" class="finish" value="Finish!"/>
 *	</form>
 *
 */

;(function($) {

	$.fn.stepy = function(settings) {
		options = $.extend({}, $.fn.stepy.defaults, settings);

		if (this.length == 0) {
			debug('Invalid selector!');
			return;
		} else if (this.length > 1) {
			return this.each(function() {
				$.fn.stepy.apply($(this), [settings]);
			});
		}

		$global = $(this);

		var id			= $global.attr('id'),
			steps		= $global.children('fieldset'),
			size		= steps.size(),
			description	= '',
			title		= '',
			step;

        var $titles = $('

').insertBefore($global);

        if (options.validate && $global.is('form')) {
        	$global.append('

');
        }

        steps.each(function(i) { // fieldset
        	step = $(this);

        	step
        	.attr('id', id + '-step-' + i)
        	.addClass('step')
        	.append('

');

        	title = (step.attr('title') != '') ? step.attr('title') : '--';

        	description = step.children('legend:first').html();

        	$titles.append('
' + title  + '' + description + '
');

        	if (i == 0) {
        		createNextButton(i);
        	} else {
        		createBackButton(i);
        		step.hide();

        		if (i != size - 1) {
	        		createNextButton(i);
	        	}
        	}
        });

        $titles.children('li:first').addClass('current-step');

        var finish = $global.children('.finish'),
        	$this	= $global,
        	opt		= options;

        if (options.finish) {
	        if (finish.length) {
        		finish
        		.hide()
        		.click(function() {
        			validate($this, size - 1, opt);
        		})
        		.appendTo($global.find('p:last'));
	        } else if ($global.is('form')) {
	        	debug('You should create a button with a class named "finish" when the attribute \'finish\' is true.');
	        }
        }

        if (options.titleClick) {
        	$titles.children().click(function() {
        		var clicked = parseInt($(this).attr('id').match(/\d/)),
        			current = parseInt($titles.children('.current-step').attr('id').match(/\d/)),
        			maxStep = clicked;

				if (clicked > current) {									// Validate only clickeds steps ahead.
					maxStep = getMaxStep($this, opt, clicked);
				}

				if (clicked != current) {									// Avoid change to the same step.
					selectStep($this, maxStep);

			        if (opt.finish && maxStep + 1 == size) {
	                	finish.show();
	                }
				}
        	});
    	} else {
    		$titles.children().css('cursor', 'default');
    	}

        function createBackButton(i) {
        	$('', {
        		id:			id + '-back-' + i,
        		href:		'javascript:void(0);',
        		'class':	'button-back',
        		html:		options.backLabel
        	})
        	.click(function() {
                selectStep($this, i - 1);
                finish.hide();
            })
        	.appendTo($('p#' + id + '-buttons-' + i));

        };

        function createNextButton(i) {
        	$('', {
        		id:			id + '-next-' + i,
        		href:		'javascript:void(0);',
        		'class':	'button-next',
        		html:		options.nextLabel
        	})
        	.click(function() {
        		var maxStep	= getMaxStep($this, opt, i + 1);

				selectStep($this, maxStep);

		        if (opt.finish && maxStep + 1 == size) {
                	finish.show();
                }
            })
            .appendTo($('p#' + id + '-buttons-' + i));
        };

        function getMaxStep(context, opt, clicked) {
        	var maxStep = clicked,
        		isValid = true;

        	if (opt.validate) {
	        	for (var i = 0; i < clicked; i++) {
					isValid = validate($this, i, opt) && isValid;	// Accumulates validations.

					if (opt.block && !isValid) {					// In the first invalid step the function stops or not.
						maxStep = i;								// The first invalid step.
						break;
					}
				}
        	}

        	return maxStep;
        };

		return $global;
	};

	$.fn.stepy.defaults = {
		backLabel:		'< Back',
		block:			false,
		errorImage:		false,
		finish:			true,
		nextLabel:		'Next >',
		titleClick:		false,
		validate:		false
	};

	$.fn.stepy.step = function(index, id) {
		selectStep(getContext(index, id, 'step'), index - 1);
		$.fn.stepy;
	};

	function debug(message) {
		if (console && console.log) {
			console.log(message);
		}
	};

	function getContext(value, id, name) {
		var context = $global;

		if (id) {
			context	= $(id);

			if (!context.length) {
				debug('"' + id + '" is a invalid ID for the public funtion $.fn.stepy.' + name + '().');
				return;
			}
		}

		return context;
	};

	function selectStep(context, index) {
		var id		= context.attr('id'),
			size	= context.children('fieldset').size(),
			step;

		if (index > size - 1) {
			index = size - 1;
		}

		context
			.children('fieldset').hide()
		.end()
			.children('fieldset')
				.eq(index).show();

		context
			.prev()
				.children().removeClass('current-step')
			.end()
			.children()
				.eq(index).addClass('current-step');

        if (context.is('form')) {
        	context
        		.children('fieldset')
	        		.eq(index)
		        		.find(':input:visible')
			        		.each(function() {
			        			step = $(this);

					        	if (!step.attr('disabled')) {
					    			step.focus();
					    			return false;
					        	}
			        		});
        }
	};

    function validate(context, index, options) {
    	if (!context.is('form')) {
    		return true;
    	}

    	var id		= context.attr('id'),
    		isValid	= true,
    		step	= context.children('fieldset').eq(index),
    		titles	= context.prev('ul.stepy-titles').children();

    	step.find(':input').each(function() {
    		isValid = isValid && context.validate().element($(this));

    		if (isValid === undefined) {
    			isValid = true;
    		}

    		if (!isValid) {
    			if (options.block) {
    				selectStep(context, index);
    			}

    			if (options.errorImage) {
    				titles.eq(index).addClass('error-image');
    			}

    			context.validate().focusInvalid();
    		} else {
    			if (options.errorImage) {
    				titles.eq(index).removeClass('error-image');
    			}
    		}
    	});

    	return isValid;
    };

})(jQuery);<commit_msg>Added attribute onBack and onNext callback to make decisions between transitions.<commit_after>/**
 * jQuery Stepy - A Wizard Plugin - http://wbotelhos.com/stepy
 * ---------------------------------------------------------------------------------
 *
 * jQuery Stepy is a plugin based on FormToWizard that generates a customizable wizard.
 *
 * Licensed under The MIT License
 *
 * @version			0.2.1
 * @since			07.03.2010
 * @author			Washington Botelho dos Santos
 * @documentation	http://wbotelhos.com/raty
 * @twitter			http://twitter.com/wbotelhos
 * @license			http://opensource.org/licenses/mit-license.php MIT
 * @package			jQuery Plugins
 *
 * Usage with default values:
 * ---------------------------------------------------------------------------------
 * $('#default').stepy();
 *
 *	<form id="default">
 *		<fieldset title="Step 1">
 *			<legend>description one</legend>
 *
 *		</fieldset>
 *
 *		<fieldset title="Step 2">
 *			<legend>description one</legend>
 *
 *		</fieldset>
 *
 *		// and so on..
 *
 *		<input type="submit" class="finish" value="Finish!"/>
 *	</form>
 *
 */

;(function($) {

	$.fn.stepy = function(settings) {
		options = $.extend({}, $.fn.stepy.defaults, settings);

		if (this.length == 0) {
			debug('Invalid selector!');
			return;
		} else if (this.length > 1) {
			return this.each(function() {
				$.fn.stepy.apply($(this), [settings]);
			});
		}

		$global = $(this);

		var id			= $global.attr('id'),
			steps		= $global.children('fieldset'),
			size		= steps.size(),
			description	= '',
			title		= '',
			step,
			$titles = $('

').insertBefore($global);

        if (options.validate && $global.is('form')) {
        	$global.append('

');
        }

        steps.each(function(index) { // fieldset
        	step = $(this);

        	step
        	.attr('id', id + '-step-' + index)
        	.addClass('step')
        	.append('

');

        	title = (step.attr('title') != '') ? step.attr('title') : '--';

        	description = step.children('legend:first').html();

        	$titles.append('
' + title  + '' + description + '
');

        	if (index == 0) {
        		createNextButton(index);
        	} else {
        		createBackButton(index);
        		step.hide();

        		if (index != size - 1) {
	        		createNextButton(index);
	        	}
        	}
        });

        $titles.children('li:first').addClass('current-step');

        var finish = $global.children('.finish'),
        	$this	= $global,
        	opt		= options;

		if (options.finish) {
	        if (finish.length) {
        		finish
        		.hide()
        		.click(function() {
        			validate($this, size - 1, opt);
        		})
        		.appendTo($global.find('p:last'));
	        } else if ($global.is('form')) {
	        	debug('You should create a button with a class named "finish" when the attribute \'finish\' is true.');
	        }
        }

        if (options.titleClick) {
        	$titles.children().click(function() {
        		var clicked = parseInt($(this).attr('id').match(/\d/)),
        			current = parseInt($titles.children('.current-step').attr('id').match(/\d/)),
        			maxStep = clicked;

				if (clicked > current) {									// Validate only clickeds steps ahead.
					if (isStopCallback(opt.onNext, clicked)) {
						return;
					}

					maxStep = getMaxStep($this, opt, clicked);
				} else if (clicked < current) {
					if (isStopCallback(opt.onBack, clicked)) {
						return;
					}
				}

				if (clicked != current) {									// Avoid change to the same step.
					selectStep($this, maxStep);

			        if (opt.finish && maxStep + 1 == size) {
	                	finish.show();
	                }
				}
        	});
    	} else {
    		$titles.children().css('cursor', 'default');
    	}

        function isStopCallback(callback, clicked) {
        	var isValid = callback.apply($this, [clicked + 1]);

        	if (isValid || isValid === undefined) {
				return false;
			}

        	return true;
        };

        function createBackButton(index) {
        	$('', {
        		id:			id + '-back-' + index,
        		href:		'javascript:void(0);',
        		'class':	'button-back',
        		html:		options.backLabel
        	})
        	.click(function() {
        		if (!isStopCallback(opt.onBack, index - 1)) {
	                selectStep($this, index - 1);
	                finish.hide();
        		}
            })
        	.appendTo($('p#' + id + '-buttons-' + index));

        };

        function createNextButton(index) {
        	$('', {
        		id:			id + '-next-' + index,
        		href:		'javascript:void(0);',
        		'class':	'button-next',
        		html:		options.nextLabel
        	})
        	.click(function() {
        		if (!isStopCallback(opt.onNext, index + 1)) {
	        		var maxStep	= getMaxStep($this, opt, index + 1);

					selectStep($this, maxStep);

			        if (opt.finish && maxStep + 1 == size) {
	                	finish.show();
	                }
        		}
            })
            .appendTo($('p#' + id + '-buttons-' + index));
        };

        function getMaxStep(context, opt, clicked) {
        	var maxStep = clicked,
        		isValid = true;

        	if (opt.validate) {
	        	for (var i = 0; i < clicked; i++) {
					isValid = validate($this, i, opt) && isValid;	// Accumulates validations.

					if (opt.block && !isValid) {					// In the first invalid step the function stops or not.
						maxStep = i;								// The first invalid step.
						break;
					}
				}
        	}

        	return maxStep;
        };

		return $global;
	};

	$.fn.stepy.defaults = {
		backLabel:		'< Back',
		block:			false,
		errorImage:		false,
		finish:			true,
		onBack:			function(index) { return true; },
		onNext:			function(index) { return true; },
		nextLabel:		'Next >',
		titleClick:		false,
		validate:		false
	};

	$.fn.stepy.step = function(index, id) {
		selectStep(getContext(index, id, 'step'), index - 1);
		$.fn.stepy;
	};

	function debug(message) {
		if (console && console.log) {
			console.log(message);
		}
	};

	function getContext(value, id, name) {
		var context = $global;

		if (id) {
			context	= $(id);

			if (!context.length) {
				debug('"' + id + '" is a invalid ID for the public funtion $.fn.stepy.' + name + '().');
				return;
			}
		}

		return context;
	};

	function selectStep(context, index) {
		var id		= context.attr('id'),
			size	= context.children('fieldset').size(),
			step;

		if (index > size - 1) {
			index = size - 1;
		}

		context
			.children('fieldset').hide()
		.end()
			.children('fieldset')
				.eq(index).show();

		context
			.prev()
				.children().removeClass('current-step')
			.end()
			.children()
				.eq(index).addClass('current-step');

        if (context.is('form')) {
        	context
        		.children('fieldset')
	        		.eq(index)
		        		.find(':input:visible')
			        		.each(function() {
			        			step = $(this);

					        	if (!step.attr('disabled')) {
					    			step.focus();
					    			return false;
					        	}
			        		});
        }
	};

    function validate(context, index, options) {
    	if (!context.is('form')) {
    		return true;
    	}

    	var id		= context.attr('id'),
    		isValid	= true,
    		step	= context.children('fieldset').eq(index),
    		titles	= context.prev('ul.stepy-titles').children();

    	step.find(':input').each(function() {
    		isValid = isValid && context.validate().element($(this));

    		if (isValid === undefined) {
    			isValid = true;
    		}

    		if (!isValid) {
    			if (options.block) {
    				selectStep(context, index);
    			}

    			if (options.errorImage) {
    				titles.eq(index).addClass('error-image');
    			}

    			context.validate().focusInvalid();
    		} else {
    			if (options.errorImage) {
    				titles.eq(index).removeClass('error-image');
    			}
    		}
    	});

    	return isValid;
    };

})(jQuery);<|endoftext|>


<commit_before>const fs = require('fs')
const appActions = require('../actions/appActions')
const siteTags = require('../constants/siteTags')
const siteUtil = require('../state/siteUtil')
const Immutable = require('immutable')
const appStoreRenderer = require('../stores/appStoreRenderer')

/**
 * Processes a single node from an exported HTML file from Firefox or Chrome
 * @param {Object} parserState - the current parser state
 * @param {Object} node - The current DOM node which is being processed
 */
function processBookmarkNode (parserState, domNode) {
  switch (domNode.tagName) {
    case 'DL':
      const backupParentFolderId = parserState.parentFolderId
      parserState.parentFolderId = parserState.lastFolderId
      for (let i = 0; i < domNode.children.length; i++) {
        processBookmarkNode(parserState, domNode.children[i])
      }
      parserState.parentFolderId = backupParentFolderId
      break
    case 'DT':
      for (let i = 0; i < domNode.children.length; i++) {
        processBookmarkNode(parserState, domNode.children[i])
      }
      break
    case 'H3':
      if (!domNode.getAttribute('PERSONAL_TOOLBAR_FOLDER')) {
        const folder = {
          title: domNode.innerText,
          folderId: parserState.nextFolderId,
          parentFolderId: parserState.parentFolderId,
          lastAccessedTime: domNode.getAttribute('LAST_MODIFIED') || domNode.getAttribute('ADD_DATE'),
          tags: [siteTags.BOOKMARK_FOLDER]
        }
        parserState.lastFolderId = parserState.nextFolderId
        parserState.nextFolderId++
        parserState.sites.push(folder)
      } else {
        parserState.lastFolderId = 0
      }
      break
    case 'A':
      // Skip over Firefox smart folders
      if (domNode.href.startsWith('place:')) {
        break
      }
      const site = {
        title: domNode.innerText,
        location: domNode.href,
        parentFolderId: parserState.parentFolderId,
        lastAccessedTime: domNode.getAttribute('LAST_MODIFIED') || domNode.getAttribute('ADD_DATE'),
        tags: [siteTags.BOOKMARK]
      }
      parserState.sites.push(site)
      break
  }
}

/**
 * Loads an html file which was exported from Chrome or another browser
 *
 * @param {string} path - The path fo the HTML file to import from
 * @return a promise which rejects on error and resolves when the import has completed,
 *   passing in an object with a importCount property.
 */
module.exports.importFromHTML = (path) => {
  return new Promise((resolve, reject) => {
    fs.readFile(path, (err, data) => {
      if (err || !data) {
        reject(err)
        return
      }
      const parser = new window.DOMParser()
      const doc = parser.parseFromString(data.toString()
        // The presence of DD tags causes the parser to think that
        // DL isn't a child of the parent DT, so get rid of them.
        // They are ignored and so are text nodes.
        .replace(/<DD>/g, ''), 'text/html')

      // Each window's appStoreRenderer holds a copy of the app state, but it's not
      // mutable, so this is only used for getting the current list of sites.
      const parserState = {
        nextFolderId: siteUtil.getNextFolderId(appStoreRenderer.state.get('sites')),
        lastFolderId: -1,
        parentFolderId: -1,
        sites: []
      }

      // Process each of the nodes starting with the first DL node
      processBookmarkNode(parserState, doc.querySelector('dl'))

      // Add the sites to the app store in the main process
      appActions.addSite(Immutable.fromJS(parserState.sites))
      resolve({importCount: parserState.sites.length})
    })
  })
}
<commit_msg>Coerce to number and store as milliseconds from importing<commit_after>const fs = require('fs')
const appActions = require('../actions/appActions')
const siteTags = require('../constants/siteTags')
const siteUtil = require('../state/siteUtil')
const Immutable = require('immutable')
const appStoreRenderer = require('../stores/appStoreRenderer')

/**
 * Processes a single node from an exported HTML file from Firefox or Chrome
 * @param {Object} parserState - the current parser state
 * @param {Object} node - The current DOM node which is being processed
 */
function processBookmarkNode (parserState, domNode) {
  switch (domNode.tagName) {
    case 'DL':
      const backupParentFolderId = parserState.parentFolderId
      parserState.parentFolderId = parserState.lastFolderId
      for (let i = 0; i < domNode.children.length; i++) {
        processBookmarkNode(parserState, domNode.children[i])
      }
      parserState.parentFolderId = backupParentFolderId
      break
    case 'DT':
      for (let i = 0; i < domNode.children.length; i++) {
        processBookmarkNode(parserState, domNode.children[i])
      }
      break
    case 'H3':
      if (!domNode.getAttribute('PERSONAL_TOOLBAR_FOLDER')) {
        const folder = {
          title: domNode.innerText,
          folderId: parserState.nextFolderId,
          parentFolderId: parserState.parentFolderId,
          lastAccessedTime: (domNode.getAttribute('LAST_MODIFIED') || domNode.getAttribute('ADD_DATE') || 0) * 1000,
          tags: [siteTags.BOOKMARK_FOLDER]
        }
        parserState.lastFolderId = parserState.nextFolderId
        parserState.nextFolderId++
        parserState.sites.push(folder)
      } else {
        parserState.lastFolderId = 0
      }
      break
    case 'A':
      // Skip over Firefox smart folders
      if (domNode.href.startsWith('place:')) {
        break
      }
      const site = {
        title: domNode.innerText,
        location: domNode.href,
        parentFolderId: parserState.parentFolderId,
        lastAccessedTime: (domNode.getAttribute('LAST_MODIFIED') || domNode.getAttribute('ADD_DATE') || 0) * 1000,
        tags: [siteTags.BOOKMARK]
      }
      parserState.sites.push(site)
      break
  }
}

/**
 * Loads an html file which was exported from Chrome or another browser
 *
 * @param {string} path - The path fo the HTML file to import from
 * @return a promise which rejects on error and resolves when the import has completed,
 *   passing in an object with a importCount property.
 */
module.exports.importFromHTML = (path) => {
  return new Promise((resolve, reject) => {
    fs.readFile(path, (err, data) => {
      if (err || !data) {
        reject(err)
        return
      }
      const parser = new window.DOMParser()
      const doc = parser.parseFromString(data.toString()
        // The presence of DD tags causes the parser to think that
        // DL isn't a child of the parent DT, so get rid of them.
        // They are ignored and so are text nodes.
        .replace(/<DD>/g, ''), 'text/html')

      // Each window's appStoreRenderer holds a copy of the app state, but it's not
      // mutable, so this is only used for getting the current list of sites.
      const parserState = {
        nextFolderId: siteUtil.getNextFolderId(appStoreRenderer.state.get('sites')),
        lastFolderId: -1,
        parentFolderId: -1,
        sites: []
      }

      // Process each of the nodes starting with the first DL node
      processBookmarkNode(parserState, doc.querySelector('dl'))

      // Add the sites to the app store in the main process
      appActions.addSite(Immutable.fromJS(parserState.sites))
      resolve({importCount: parserState.sites.length})
    })
  })
}
<|endoftext|>


<commit_before>define([
    "dojo/Evented",
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dijit/_WidgetBase",
    "dijit/_OnDijitClickMixin",
    "dijit/_TemplatedMixin",
    "dojo/on",
    // load template
    "dojo/text!./templates/locateButton.html",
    "dojo/i18n!./nls/locateButton",
    "dojo/dom",
    "dojo/dom-class",
    "dojo/dom-style",
    "esri/geometry/webMercatorUtils",
    "esri/geometry/Point",
    "esri/SpatialReference",
    "esri/graphic",
    "esri/symbols/PictureMarkerSymbol"
],
function (
    Evented,
    declare,
    lang,
    _WidgetBase, _OnDijitClickMixin, _TemplatedMixin,
    on,
    dijitTemplate, i18n,
    dom, domClass, domStyle,
    webMercatorUtils, Point, SpatialReference,
    Graphic, PictureMarkerSymbol
) {
    return declare([_WidgetBase, _OnDijitClickMixin, _TemplatedMixin], {
        declaredClass: "modules.locateButton",
        templateString: dijitTemplate,
        options: {
            theme: "locateButton",
            map: null,
            visible: true,
            locateLOD: 16,
            showPointer: true,
            pointerGraphic: new Graphic(null, new PictureMarkerSymbol('images/bluedot_retina.png', 21, 21)),
            locateSettings: {
                maximumAge: 3000,
                timeout: 1000,
                enableHighAccuracy: true
            }
        },
        // lifecycle: 1
        constructor: function(options, srcRefNode) {
            // mix in settings and defaults
            declare.safeMixin(this.options, options);
            // widget node
            this.domNode = srcRefNode;
            this._i18n = i18n;
            if (!navigator.geolocation) {
                this.options.visible = false;
            }
            // properties
            this.set("map", this.options.map);
            this.set("locateLOD", this.options.locateLOD);
            this.set("theme", this.options.theme);
            this.set("visible", this.options.visible);
            this.set("showPointer", this.options.showPointer);
            this.set("pointerGraphic", this.options.pointerGraphic);
            // listeners
            this.watch("theme", this._updateThemeWatch);
            this.watch("visible", this._visible);
            // classes
            this._css = {
                container: "locateCon",
                locate: "zoomLocateButton",
                loading: "loading"
            };
        },
        // start widget. called by user
        startup: function() {
            // map not defined
            if (!this.map) {
                this.destroy();
                return new Error('map required');
            }
            // map domNode
            this._mapNode = dom.byId(this.map.id);
            // when map is loaded
            if (this.map.loaded) {
                this._init();
            } else {
                on(this.map, "load", lang.hitch(this, function() {
                    this._init();
                }));
            }
        },
        // connections/subscriptions will be cleaned up during the destroy() lifecycle phase
        destroy: function() {
            this.inherited(arguments);
        },
        /* ---------------- */
        /* Public Events */
        /* ---------------- */
        onLoad: function() {
            this.set("loaded", true);
        },
        onLocate: function(){
            this.emit("located", this.get("pointerGraphic"));
        },
        /* ---------------- */
        /* Public Functions */
        /* ---------------- */
        clear: function(){
            if(this.get("pointerGraphic")){
                this.map.graphics.remove(this.get("pointerGraphic"));
            }
        },
        locate: function() {
            this._showLoading();
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(lang.hitch(this, function(position) {
                    if (position) {
                        var latitude = position.coords.latitude;
                        var longitude = position.coords.longitude;
                        // set point
                        var pt = webMercatorUtils.geographicToWebMercator(new Point(longitude, latitude, new SpatialReference(4326)));
                        if(pt){
                            return this.map.centerAndZoom(pt, this.get("locateLOD")).then(lang.hitch(this, function(){
                                if(this.get("showPointer")){
                                    this.clear();
                                }
                                var attributes = this.get("pointerGraphic").attributes || {};
                                attributes.position = position;
                                var newGraphic = this.get("pointerGraphic").setGeometry(pt).setAttributes(attributes);
                                this.set("pointerGraphic", newGraphic);
                                this.onLocate();
                                if(this.get("showPointer")){
                                    this.map.graphics.add(this.get("pointerGraphic"));
                                }
                                this._hideLoading();
                            }));
                        }
                        else{
                            this._hideLoading();
                            return new Error('Invalid point');
                        }
                    }
                    else{
                        this._hideLoading();
                        return new Error('Invalid position');
                    }
                }), lang.hitch(this, function(err) {
                    this._hideLoading();
                    return err;
                }), this.options.locateSettings);
            }
            else{
                this._hideLoading();
                return new Error('geolocation unsupported');
            }
        },
        show: function(){
            this.set("visible", true);
        },
        hide: function(){
            this.set("visible", false);
        },
        /* ---------------- */
        /* Private Functions */
        /* ---------------- */
        _showLoading: function(){
            domClass.add(this._locateNode, this._css.loading);
        },
        _hideLoading: function(){
            domClass.remove(this._locateNode, this._css.loading);
        },
        _init: function() {
            this._visible();
            this.onLoad();
        },
        _updateThemeWatch: function(attr, oldVal, newVal) {
            domClass.remove(this.domNode, oldVal);
            domClass.add(this.domNode, newVal);
        },
        _visible: function(){
            if(this.get("visible")){
                domStyle.set(this.domNode, 'display', 'block');
            }
            else{
                domStyle.set(this.domNode, 'display', 'none');
            }
        }
    });
});<commit_msg>set scale via accuracy<commit_after>define([
    "dojo/Evented",
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dijit/_WidgetBase",
    "dijit/_OnDijitClickMixin",
    "dijit/_TemplatedMixin",
    "dojo/on",
    // load template
    "dojo/text!./templates/locateButton.html",
    "dojo/i18n!./nls/locateButton",
    "dojo/dom",
    "dojo/dom-class",
    "dojo/dom-style",
    "esri/geometry/webMercatorUtils",
    "esri/geometry/Point",
    "esri/SpatialReference",
    "esri/graphic",
    "esri/symbols/PictureMarkerSymbol"
],
function (
    Evented,
    declare,
    lang,
    _WidgetBase, _OnDijitClickMixin, _TemplatedMixin,
    on,
    dijitTemplate, i18n,
    dom, domClass, domStyle,
    webMercatorUtils, Point, SpatialReference,
    Graphic, PictureMarkerSymbol
) {
    return declare([_WidgetBase, _OnDijitClickMixin, _TemplatedMixin], {
        declaredClass: "modules.locateButton",
        templateString: dijitTemplate,
        options: {
            theme: "locateButton",
            map: null,
            visible: true,
            showPointer: true,
            pointerGraphic: new Graphic(null, new PictureMarkerSymbol('images/bluedot_retina.png', 21, 21)),
            locateSettings: {
                maximumAge: 3000,
                timeout: 1000,
                enableHighAccuracy: true
            }
        },
        // lifecycle: 1
        constructor: function(options, srcRefNode) {
            // mix in settings and defaults
            declare.safeMixin(this.options, options);
            // widget node
            this.domNode = srcRefNode;
            this._i18n = i18n;
            if (!navigator.geolocation) {
                this.options.visible = false;
            }
            // properties
            this.set("map", this.options.map);
            this.set("theme", this.options.theme);
            this.set("visible", this.options.visible);
            this.set("showPointer", this.options.showPointer);
            this.set("pointerGraphic", this.options.pointerGraphic);
            // listeners
            this.watch("theme", this._updateThemeWatch);
            this.watch("visible", this._visible);
            // classes
            this._css = {
                container: "locateCon",
                locate: "zoomLocateButton",
                loading: "loading"
            };
        },
        // start widget. called by user
        startup: function() {
            // map not defined
            if (!this.map) {
                this.destroy();
                return new Error('map required');
            }
            // map domNode
            this._mapNode = dom.byId(this.map.id);
            // when map is loaded
            if (this.map.loaded) {
                this._init();
            } else {
                on(this.map, "load", lang.hitch(this, function() {
                    this._init();
                }));
            }
        },
        // connections/subscriptions will be cleaned up during the destroy() lifecycle phase
        destroy: function() {
            this.inherited(arguments);
        },
        /* ---------------- */
        /* Public Events */
        /* ---------------- */
        onLoad: function() {
            this.set("loaded", true);
        },
        onLocate: function(){
            this.emit("located", this.get("pointerGraphic"));
        },
        /* ---------------- */
        /* Public Functions */
        /* ---------------- */
        clear: function(){
            if(this.get("pointerGraphic")){
                this.map.graphics.remove(this.get("pointerGraphic"));
            }
        },
        locate: function() {
            this._showLoading();
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(lang.hitch(this, function(position) {
                    if (position) {
                        var latitude = position.coords.latitude;
                        var longitude = position.coords.longitude;
                        var accuracy = position.coords.accuracy || 50000;
                        // set point
                        var pt = webMercatorUtils.geographicToWebMercator(new Point(longitude, latitude, new SpatialReference(4326)));
                        if(pt){
                            this.map.setScale(accuracy);
                            return this.map.centerAt(pt).then(lang.hitch(this, function(){
                                if(this.get("showPointer")){
                                    this.clear();
                                }
                                var attributes = this.get("pointerGraphic").attributes || {};
                                attributes.position = position;
                                var newGraphic = this.get("pointerGraphic").setGeometry(pt).setAttributes(attributes);
                                this.set("pointerGraphic", newGraphic);
                                this.onLocate();
                                if(this.get("showPointer")){
                                    this.map.graphics.add(this.get("pointerGraphic"));
                                }
                                this._hideLoading();
                            }));
                        }
                        else{
                            this._hideLoading();
                            return new Error('Invalid point');
                        }
                    }
                    else{
                        this._hideLoading();
                        return new Error('Invalid position');
                    }
                }), lang.hitch(this, function(err) {
                    this._hideLoading();
                    return err;
                }), this.options.locateSettings);
            }
            else{
                this._hideLoading();
                return new Error('geolocation unsupported');
            }
        },
        show: function(){
            this.set("visible", true);
        },
        hide: function(){
            this.set("visible", false);
        },
        /* ---------------- */
        /* Private Functions */
        /* ---------------- */
        _showLoading: function(){
            domClass.add(this._locateNode, this._css.loading);
        },
        _hideLoading: function(){
            domClass.remove(this._locateNode, this._css.loading);
        },
        _init: function() {
            this._visible();
            this.onLoad();
        },
        _updateThemeWatch: function(attr, oldVal, newVal) {
            domClass.remove(this.domNode, oldVal);
            domClass.add(this.domNode, newVal);
        },
        _visible: function(){
            if(this.get("visible")){
                domStyle.set(this.domNode, 'display', 'block');
            }
            else{
                domStyle.set(this.domNode, 'display', 'none');
            }
        }
    });
});<|endoftext|>


<commit_before>(function () {

  angular.module('ngMinimalGrid', [])
    .provider('minimalGridConfig',function(){
      this.statsMessage = 'Showing %1 to %2 of %3 results'
      this.setStatsMessage = function(message){
        this.statsMessage = message
        return this
      }

      this.firstButtonLabel = 'First'
      this.setFirstLabel = function(label){
        this.firstButtonLabel = label
        return this
      }

      this.lastButtonLabel = 'Last'
      this.setLastLabel = function(label){
        this.lastButtonLabel = label
        return this
      }

      this.$get = function(){
        return this
      }
    })
    .directive('minimalGrid', ['minimalGridConfig', '$parse', '$filter', function (minimalGridConfig, $parse, $filter) {
      return {
        restrict: 'E',
        scope: {
          columns: '<',
          rows: '<',
          fake: '<?',
          totalRows: '<?',
          paginationMax: '<?',
          paginationRange: '<?',
          changeOrderByCallback: '&?onChangeOrderBy',
          changePaginateCallback: '&?onChangePaginate',
          clickRowCallback: '&?onClickRow'
        },
        template:
        '

' +
        '
' +
        '
' +
        '
' +
        '      {{ column.title }}	' +
        '
' +
        '
' +
        '
' +
        '
' +
        '      	' +
        '
' +
        '
' +
        '
' +
        '
' +
        '
' +
        '
{{ firstButtonLabel }}
' +
        '
' +
        '      ' +
        '        << ' +
        '
' +
        '
{{ n }}
' +
        '
 >>
' +
        '
{{ lastButtonLabel }}
' +
        '
' +
        '
' +
        '

',
        link: function (scope) {

          scope.firstButtonLabel = minimalGridConfig.firstButtonLabel
          scope.lastButtonLabel = minimalGridConfig.lastButtonLabel

          // model
          scope.$watchCollection('rows', function (newRows) {
            setData(newRows)

            if (!scope.fake) {
              updatePagesTotal(scope.data.length)
              updatePages()

              if (scope._lastColumnOrderBy) scope.changeOrderBy(scope._lastColumnOrderBy)
              if (scope._lastPagePaginate) scope.changePaginate(scope._lastPagePaginate)
            }
          })

          if (scope.fake || scope.totalRows) {
            scope.$watch('totalRows', function (newTotal) {
              scope._lastTotalPopulatePages = newTotal
              updatePagesTotal(newTotal)
              updatePages()
            })
          }

          // local binds
          scope.columnParse = function (assign, obj, columns) {
            var getter = $parse(assign)
            var value = getter(obj)
            if (columns.formatDate) {
              value = $filter('date')(value * 1000, columns.formatDate, '+0000')
            }
            columns.onRender = columns.onRender || function (val) { return val }
            return columns.onRender(value)
          }

          scope.statsParse = function () {
            var message = minimalGridConfig.statsMessage
            var first = ((scope.pages.current - 1) * scope.pages.max) > 0 ? ((scope.pages.current - 1) * scope.pages.max) + 1 : (scope._data.length > 0) ? 1 : 0;
            if (!scope.fake) {
              var last = (((scope.pages.current - 1) * scope.pages.max) + scope.pages.max) < scope._data.length ? (((scope.pages.current - 1) * scope.pages.max) + scope.pages.max) : scope._data.length
              var total = scope._data.length
            } else {
              if (scope._lastTotalPopulatePages != undefined) {
                var last = (((scope.pages.current - 1) * scope.pages.max) + scope.pages.max) < scope._lastTotalPopulatePages ? (((scope.pages.current - 1) * scope.pages.max) + scope.pages.max) : scope._lastTotalPopulatePages
                var total = scope._lastTotalPopulatePages
              } else {
                var last = 0
                var total = 0
              }
            }
            return message.replace('%1', first).replace('%2', last).replace('%3', total)
          }

          scope.changeOrderBy = function (column) {
            if (scope._lastColumnOrderBy != column) {
              var classes = column.class
              scope.columns.map(function (val) {
                val.class = 'sorting'
              })
              column.class = (classes == 'sorting_asc') ? 'sorting_desc' : 'sorting_asc'

              scope._lastColumnOrderBy = Object.assign({}, column)
            }

            if (!scope.fake) {
              if (scope.pages.current != 1) {
                scope.pages.current = 1
                setData(scope._data)
                updatePages()
              }

              var data = $filter('orderBy')(scope.data, column.key, (column.class == 'sorting_desc'))
              setData(data)
            }

            if (scope.changeOrderByCallback) {
              scope.changeOrderByCallback({
                orderBy: {
                  orderdirection: column.class.replace('sorting_', ''),
                  orderby: column.key
                }
              })
            }

          }

          scope.changePaginate = function (page) {
            scope._lastPagePaginate = Number(page)
            scope.pages.current = page

            updatePages()

            if (!scope.fake) {
              setData(scope._data)
              var cut = (scope.pages.current - 1) > 0 ? (scope.pages.current - 1) * scope.pages.max : 0
              scope.data = scope.data.slice(cut)
            }

            if (scope.changePaginateCallback) {
              scope.changePaginateCallback({ pages: scope.pages })
            }
          }

          scope.clickRow = function (row) {
            if (scope.clickRowCallback) {
              scope.clickRowCallback({ row: row })
            }
          }

          // local functions
          function updatePagesTotal(totalItems) {
            scope.pages.total = []
            var totalPages = Math.ceil(totalItems / scope.pages.max)
            for (var x = 1; x <= totalPages; x++) scope.pages.total.push(x)
          }

          function updatePages() {
            if (scope.pages.current > scope.pages.total.length) {
              scope.pages.current = 1
              scope._lastPagePaginate = 1
            }

            scope.pages.first = 1
            scope.pages.last = scope.pages.total.length
            scope.pages.previous = ((scope.pages.current - 1) > 0) ? (scope.pages.current - 1) : 1
            scope.pages.next = ((scope.pages.current + 1) <= scope.pages.total.length) ? (scope.pages.current + 1) : scope.pages.total.length

            scope.pages.pagination = getPagination()
          }

          function getPagination() {
            var pagination = 0

            if (pagination < scope.pages.range) pagination = scope.pages.current - Math.ceil(scope.pages.range/2)

            var diffTotalRange = (scope.pages.total.length - scope.pages.range)
            if (pagination > diffTotalRange) pagination = diffTotalRange

            if (pagination < 0) pagination = 0

            return pagination
          }

          function setData(data) {
            scope._data = data
            scope.data = Object.assign([], scope._data)
          }

          scope._data = []
          scope.data = []

          scope._lastColumnOrderBy = undefined
          scope._lastPagePaginate = undefined
          scope._lastTotalPopulatePages = undefined

          // behavior control
          scope.fake = scope.fake || false

          // column control
          scope.columns.map(function (val) {
            val.class = 'sorting'
          })

          scope.pages = {
            first: 1,
            last: 1,
            previous: 1,
            next: 1,
            current: 1,
            total: [1],
            max: scope.paginationMax || 10,
            range: scope.paginationRange || 5,
            pagination: 0
          }
        }
      }
    }])

})();
<commit_msg>Added scope checks to throw errors<commit_after>(function () {

  angular.module('ngMinimalGrid', [])
    .provider('minimalGridConfig',function(){
      this.statsMessage = 'Showing %1 to %2 of %3 results'
      this.setStatsMessage = function(message){
        this.statsMessage = message
        return this
      }

      this.firstButtonLabel = 'First'
      this.setFirstLabel = function(label){
        this.firstButtonLabel = label
        return this
      }

      this.lastButtonLabel = 'Last'
      this.setLastLabel = function(label){
        this.lastButtonLabel = label
        return this
      }

      this.$get = function(){
        return this
      }
    })
    .directive('minimalGrid', ['minimalGridConfig', '$parse', '$filter', function (minimalGridConfig, $parse, $filter) {
      return {
        restrict: 'E',
        scope: {
          columns: '<',
          rows: '<',
          fake: '<?',
          totalRows: '<?',
          paginationMax: '<?',
          paginationRange: '<?',
          changeOrderByCallback: '&?onChangeOrderBy',
          changePaginateCallback: '&?onChangePaginate',
          clickRowCallback: '&?onClickRow'
        },
        template:
        '

' +
        '
' +
        '
' +
        '
' +
        '      {{ column.title }}	' +
        '
' +
        '
' +
        '
' +
        '
' +
        '      	' +
        '
' +
        '
' +
        '
' +
        '
' +
        '
' +
        '
{{ firstButtonLabel }}
' +
        '
' +
        '      ' +
        '        << ' +
        '
' +
        '
{{ n }}
' +
        '
 >>
' +
        '
{{ lastButtonLabel }}
' +
        '
' +
        '
' +
        '

',
        link: function (scope) {

          scope.firstButtonLabel = minimalGridConfig.firstButtonLabel
          scope.lastButtonLabel = minimalGridConfig.lastButtonLabel

          // model
          if (!angular.isArray(scope.rows)){
            throw new Error('minimalGrid error: rows must be an Array')
          }
          scope.$watchCollection('rows', function (newRows) {
            setData(newRows)

            if (!scope.fake) {
              updatePagesTotal(scope.data.length)
              updatePages()

              if (scope._lastColumnOrderBy) scope.changeOrderBy(scope._lastColumnOrderBy)
              if (scope._lastPagePaginate) scope.changePaginate(scope._lastPagePaginate)
            }
          })

          if (scope.fake || scope.totalRows) {
            scope.$watch('totalRows', function (newTotal) {
              scope._lastTotalPopulatePages = newTotal
              updatePagesTotal(newTotal)
              updatePages()
            })
          }

          // local binds
          scope.columnParse = function (assign, obj, columns) {
            var getter = $parse(assign)
            var value = getter(obj)
            if (columns.formatDate) {
              value = $filter('date')(value * 1000, columns.formatDate, '+0000')
            }
            columns.onRender = columns.onRender || function (val) { return val }
            return columns.onRender(value)
          }

          scope.statsParse = function () {
            var message = minimalGridConfig.statsMessage
            var first = ((scope.pages.current - 1) * scope.pages.max) > 0 ? ((scope.pages.current - 1) * scope.pages.max) + 1 : (scope._data.length > 0) ? 1 : 0;
            if (!scope.fake) {
              var last = (((scope.pages.current - 1) * scope.pages.max) + scope.pages.max) < scope._data.length ? (((scope.pages.current - 1) * scope.pages.max) + scope.pages.max) : scope._data.length
              var total = scope._data.length
            } else {
              if (scope._lastTotalPopulatePages != undefined) {
                var last = (((scope.pages.current - 1) * scope.pages.max) + scope.pages.max) < scope._lastTotalPopulatePages ? (((scope.pages.current - 1) * scope.pages.max) + scope.pages.max) : scope._lastTotalPopulatePages
                var total = scope._lastTotalPopulatePages
              } else {
                var last = 0
                var total = 0
              }
            }
            return message.replace('%1', first).replace('%2', last).replace('%3', total)
          }

          scope.changeOrderBy = function (column) {
            if (scope._lastColumnOrderBy != column) {
              var classes = column.class
              scope.columns.map(function (val) {
                val.class = 'sorting'
              })
              column.class = (classes == 'sorting_asc') ? 'sorting_desc' : 'sorting_asc'

              scope._lastColumnOrderBy = Object.assign({}, column)
            }

            if (!scope.fake) {
              if (scope.pages.current != 1) {
                scope.pages.current = 1
                setData(scope._data)
                updatePages()
              }

              var data = $filter('orderBy')(scope.data, column.key, (column.class == 'sorting_desc'))
              setData(data)
            }

            if (angular.isDefined(scope.changeOrderByCallback)) {
              if (!angular.isFunction(scope.changeOrderByCallback)){
                throw new Error('minimalGrid error: on-change-order-by must be a Function')
              }

              scope.changeOrderByCallback({
                orderBy: {
                  orderdirection: column.class.replace('sorting_', ''),
                  orderby: column.key
                }
              })
            }

          }

          scope.changePaginate = function (page) {
            scope._lastPagePaginate = Number(page)
            scope.pages.current = page

            updatePages()

            if (!scope.fake) {
              setData(scope._data)
              var cut = (scope.pages.current - 1) > 0 ? (scope.pages.current - 1) * scope.pages.max : 0
              scope.data = scope.data.slice(cut)
            }

            if (scope.changePaginateCallback) {
              scope.changePaginateCallback({ pages: scope.pages })
            }
          }

          scope.clickRow = function (row) {
            if (scope.clickRowCallback) {
              scope.clickRowCallback({ row: row })
            }
          }

          // local functions
          function updatePagesTotal(totalItems) {
            scope.pages.total = []
            var totalPages = Math.ceil(totalItems / scope.pages.max)
            for (var x = 1; x <= totalPages; x++) scope.pages.total.push(x)
          }

          function updatePages() {
            if (scope.pages.current > scope.pages.total.length) {
              scope.pages.current = 1
              scope._lastPagePaginate = 1
            }

            scope.pages.first = 1
            scope.pages.last = scope.pages.total.length
            scope.pages.previous = ((scope.pages.current - 1) > 0) ? (scope.pages.current - 1) : 1
            scope.pages.next = ((scope.pages.current + 1) <= scope.pages.total.length) ? (scope.pages.current + 1) : scope.pages.total.length

            scope.pages.pagination = getPagination()
          }

          function getPagination() {
            var pagination = 0

            if (pagination < scope.pages.range) pagination = scope.pages.current - Math.ceil(scope.pages.range/2)

            var diffTotalRange = (scope.pages.total.length - scope.pages.range)
            if (pagination > diffTotalRange) pagination = diffTotalRange

            if (pagination < 0) pagination = 0

            return pagination
          }

          function setData(data) {
            scope._data = data
            scope.data = Object.assign([], scope._data)
          }

          scope._data = []
          scope.data = []

          scope._lastColumnOrderBy = undefined
          scope._lastPagePaginate = undefined
          scope._lastTotalPopulatePages = undefined

          // behavior control
          scope.fake = scope.fake || false

          // column control
          if (!angular.isArray(scope.columns)){
            throw new Error('minimalGrid error: columns must be an Array')
          }
          scope.columns.map(function (val) {
            val.class = 'sorting'
          })

          if (angular.isDefined(scope.paginationMax) && !angular.isNumber(scope.paginationMax)){
            throw new Error('minimalGrid error: pagination-max must be a Number')
          }

          if (angular.isDefined(scope.paginationRange) && !angular.isNumber(scope.paginationRange)){
            throw new Error('minimalGrid error: pagination-range must be a Number')
          }
          scope.pages = {
            first: 1,
            last: 1,
            previous: 1,
            next: 1,
            current: 1,
            total: [1],
            max: scope.paginationMax || 10,
            range: scope.paginationRange || 5,
            pagination: 0
          }
        }
      }
    }])

})();
<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado Boulder

/**
 * Class that defines the shape and common functionality for a 'bucket', which
 * is container into which some sort of model objects may be placed.  This is
 * a model object in the Model-View-Controller paradigm, and requires a
 * counterpart in the view in order to be presented to the user.
 *

 * In general, this is intended to be a base class, and subclasses should be
 * used to add specific functionality, such as how other model objects are
 * added to and removed from the bucket.
 *

 * One other important note: The position of the bucket in model space is
 * based on the center of the bucket's opening.
 *
 * @author John Blanco
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  'use strict';

  var Vector2 = require( 'DOT/Vector2' );
  var Dimension2 = require( 'DOT/Dimension2' );
  var Shape = require( 'KITE/Shape' );

  // Proportion of the total height which the ellipse that represents
  // the hole occupies.  It is assumed that the width of the hole
  // is the same as the width specified at construction.
  var HOLE_ELLIPSE_HEIGHT_PROPORTION = 0.25;

  var Bucket = function( options ) {
    options = _.extend( {
      // defaults
      position: options.position || Vector2.ZERO,
      size: new Dimension2( options.width || 200, options.height || 50 ),
      baseColor: '#ff0000',
      caption: 'Set a caption!',
      captionColor: 'white'
    }, options );

    // The position is defined to be where the center of the hole is.
    this.position = options.position;

    // Base color of the bucket.
    this.baseColor = options.baseColor;

    // Caption to be shown on the bucket.
    this.captionText = options.caption;

    // Color for the caption.
    this.captionColor = options.captionColor;

    this.size = options.size;
    var size = this.size;

    var holeRadiusX = size.width / 2;
    var holeRadiusY = size.height * HOLE_ELLIPSE_HEIGHT_PROPORTION / 2;

    // Create the shape of the bucket's hole.
    this.holeShape = Shape.ellipse( 0, 0, holeRadiusX, holeRadiusY );

    // Create the shape of the container.  This code is a bit 'tweaky',
    // meaning that there are a lot of fractional multipliers in here
    // to try to achieve the desired pseudo-3D look.  The intent is
    // that the 'tilt' of the bucket can be changed without needing to
    // rework this code.
    var containerHeight = size.height * ( 1 - ( HOLE_ELLIPSE_HEIGHT_PROPORTION / 2 ) );
    this.containerShape = new Shape().moveTo( -size.width * 0.5, 0 )
      .lineTo( -size.width * 0.4, -containerHeight * 0.8 )
      .cubicCurveTo(
        -size.width * 0.3,
        -containerHeight,
        size.width * 0.3,
        -containerHeight,
        size.width * 0.4,
        -containerHeight * 0.8 )
      .lineTo( size.width * 0.5, 0 )
      .cubicCurveTo(
        size.width * 0.3,
        -containerHeight * 0.2,
        -size.width * 0.3,
        -containerHeight * 0.2,
        -size.width * 0.5,
        0 )
      .close();
  };

  return Bucket;
} );
<commit_msg>Readability reformat<commit_after>// Copyright 2002-2013, University of Colorado Boulder

/**
 * Class that defines the shape and common functionality for a 'bucket', which
 * is container into which some sort of model objects may be placed.  This is
 * a model object in the Model-View-Controller paradigm, and requires a
 * counterpart in the view in order to be presented to the user.
 *

 * In general, this is intended to be a base class, and subclasses should be
 * used to add specific functionality, such as how other model objects are
 * added to and removed from the bucket.
 *

 * One other important note: The position of the bucket in model space is
 * based on the center of the bucket's opening.
 *
 * @author John Blanco
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  'use strict';

  var Vector2 = require( 'DOT/Vector2' );
  var Dimension2 = require( 'DOT/Dimension2' );
  var Shape = require( 'KITE/Shape' );

  // Proportion of the total height which the ellipse that represents
  // the hole occupies.  It is assumed that the width of the hole
  // is the same as the width specified at construction.
  var HOLE_ELLIPSE_HEIGHT_PROPORTION = 0.25;

  var Bucket = function( options ) {
    options = _.extend( {
      // defaults
      position: options.position || Vector2.ZERO,
      size: new Dimension2( options.width || 200, options.height || 50 ),
      baseColor: '#ff0000',
      caption: 'Set a caption!',
      captionColor: 'white'
    }, options );

    // The position is defined to be where the center of the hole is.
    this.position = options.position;

    // Base color of the bucket.
    this.baseColor = options.baseColor;

    // Caption to be shown on the bucket.
    this.captionText = options.caption;

    // Color for the caption.
    this.captionColor = options.captionColor;

    this.size = options.size;
    var size = this.size;

    var holeRadiusX = size.width / 2;
    var holeRadiusY = size.height * HOLE_ELLIPSE_HEIGHT_PROPORTION / 2;

    // Create the shape of the bucket's hole.
    this.holeShape = Shape.ellipse( 0, 0, holeRadiusX, holeRadiusY );

    // Create the shape of the container.  This code is a bit 'tweaky',
    // meaning that there are a lot of fractional multipliers in here
    // to try to achieve the desired pseudo-3D look.  The intent is
    // that the 'tilt' of the bucket can be changed without needing to
    // rework this code.
    var containerHeight = size.height * ( 1 - ( HOLE_ELLIPSE_HEIGHT_PROPORTION / 2 ) );
    this.containerShape = new Shape().moveTo( -size.width * 0.5, 0 )
                                     .lineTo( -size.width * 0.4, -containerHeight * 0.8 )
                                     .cubicCurveTo( -size.width * 0.3, -containerHeight,
                                                    size.width * 0.3,  -containerHeight,
                                                    size.width * 0.4,  -containerHeight * 0.8 )
                                     .lineTo( size.width * 0.5, 0 )
                                     .cubicCurveTo( size.width * 0.3,  -containerHeight * 0.2,
                                                    -size.width * 0.3, -containerHeight * 0.2,
                                                    -size.width * 0.5, 0 )
                                     .close();
  };

  return Bucket;
} );
<|endoftext|>


<commit_before>AppModules.Echo = function (self) {
  var list = [];
  return function(msg){
    list.push(msg);
    if(list.length>3) list=list.slice(-3);
    $('#echo').html('<p>'+list.join('<p>'));
  };
};<commit_msg>add timestamp<commit_after>AppModules.Echo = function (self) {
  var list = [];
  return function(msg){
    list.push(msg);
    if(list.length>3) list=list.slice(-3);
    $('#echo').html('<p>'+(new Date()).toLocaleTimeString()+list.join('<p>'));
  };
};<|endoftext|>


<commit_before>function ajax(url, method, params, callback) {
    var obj;

    try {
        obj = new XMLHttpRequest();
    } catch (e) {
        try {
            obj = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                obj = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("Your browser does not support Ajax.");
                return false;
            }
        }
    }
    obj.onreadystatechange = function () {
        if (obj.readyState == 4) {
            callback(obj);
        }
    };
    obj.open(method, url, true);
    obj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    obj.send(params);

    return obj;
}

var
    $ = function (id) {
        return document.getElementById(id);
    },
    container = $('example1'),
    exampleConsole = $('example1console'),
    autosave = $('autosave'),
    load = $('load'),
    save = $('save'),
    reload = $('reload'),
    autosaveNotification,
    hot,
    number;

hot = new Handsontable(container, {
    startRows: 8,
    startCols: 6,
    columns: [
        { data: "id" },
        { data: "name" },
        { data: "className" },
        { data: "shape" },
        { data: "text" },
        { data: "image", renderer: coverRenderer },
        { data: "image2", renderer: coverRenderer },
        { data: "loaded" },
        {
            data: "style.lineWidth",
            type: 'dropdown',
            source: ['yellow', 'red', 'orange', 'green']
        }, {
            data: "style.radius",
            type: 'dropdown',
            source: ['1px', '2px', '3px']
        }, {
            data: "style.lineColor",
            type: 'dropdown',
            source: ['yellow', 'red', 'orange', 'green']
        }
    ],
    currentRowClassName: 'currentRow',
    rowHeaders: true,
    rowHeights: 60,
    colHeaders: ["ID", "Nombre", "ClassName", "Figura", "Descripción", "Imagen", "Imagen2", "Cargado", "Longitud linea", "Radio", "Color de línea"],
    colWidths: [70, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
    minSpareRows: 1,
    width: 600,
    height: 400,
    persistentState: true,
    contextMenu: true,
    afterChange: function (change, source) {
        if (source === 'loadData') {
            return; //don't save this change
        }
        if (!autosave.checked) {
            return;
        }
        clearTimeout(autosaveNotification);
        ajax('json/save.json', 'GET', JSON.stringify({ data: change }), function (data) {
            exampleConsole.innerText = 'Autosaved (' + change.length + ' ' + 'cell' + (change.length > 1 ? 's' : '') + ')';
            autosaveNotification = setTimeout(function () {
                exampleConsole.innerText = 'Changes will be autosaved';
            }, 1000);
        });
    }
});

hot.updateSettings({
    contextMenu: {
        callback: function (key, options) {
            if (key === 'edit') {
                number = (hot.getSelected()[0]);
                document.getElementById("dialog-with-list-activation").disabled = false;
                (function () {
                    var dialogScrollable = new mdc.dialog.MDCDialog(document.querySelector('#mdc-dialog-with-list'));
                    document.querySelector('#dialog-with-list-activation').addEventListener('click', function (evt) {
                        dialogScrollable.lastFocusedTarget = evt.target;
                        dialogScrollable.show();
                    });
                })();
                (function () {
                    // Hack to work around style-loader async loading styles
                    setTimeout(function () {
                        mdc.ripple.MDCRipple.attachTo(document.querySelector('#dialog-with-list-activation'));
                    }, 200);
                })();
                //document.getElementById("dialog-with-list-activation").disabled = true;
            }
        },
        items: {
            'row_above': {
                name: "Insertar fila encima"
            }, 'row_below': { name: "Insertar debajo" }, 'remove_row': { name: "Eliminar fila" },
            "edit": {
                name: 'Habilitar edición',
                //isHtmlName: true,
                disabled: function () {
                    // if first row, disable this option
                    return !(hot.getSelected()[0, 2, 0, 3] === 0)
                }
            }
        }
    }
})

function coverRenderer(instance, td, row, col, prop, value, cellProperties) {
    var escaped = Handsontable.helper.stringify(value),
        img;

    if (escaped.indexOf('http') === 0 || escaped.indexOf('data:image') === 0) {
        img = document.createElement('IMG');
        img.src = value;
        img.setAttribute('style', 'border-radius: 50%')
        img.setAttribute('width', '50px')
        img.setAttribute('heigth', '50px')

        Handsontable.dom.addEvent(img, 'mousedown', function (e) {
            e.preventDefault(); // prevent selection quirk
        });

        Handsontable.dom.empty(td);
        td.appendChild(img);
    }
    else {
        // render as text
        Handsontable.renderers.TextRenderer.apply(this, arguments);
    }

    return td;
}

// Handsontable.dom.addEvent(load, 'click', function () {
//     var input, file, fr, list_images = {}, dataTotal, data;

//     if (typeof window.FileReader !== 'function') {
//         alert("The file API isn't supported on this browser yet.");
//         return;
//     }

//     input = document.getElementById('fileinput');
//     if (!input) {
//         alert("Um, couldn't find the fileinput element.");
//     }
//     else if (!input.files) {
//         alert("This browser doesn't seem to support the `files` property of file inputs.");
//     }
//     else if (!input.files[0]) {
//         alert("Por favor, selecciona un archivo.");
//     }
//     else {
//         file = input.files[0];
//         fr = new FileReader();
//         fr.onload = receivedText;
//         fr.readAsText(file);
//     }

//     function receivedText(e) {
//         lines = e.target.result;
//         dataTotal = JSON.parse("{ \"data\":" + lines + "}");
//         data = dataTotal.data;
//         console.log("NODES: "+ data.nodes)

//         $('#accept').on('click', function () {
//             if (currentImage != undefined) {
//                 document.getElementById("crop").src = currentImage
//                 list_images[number] = currentImage
//                 for (var n in list_images) {
//                     data.nodes[n].image = list_images[n]
//                 }
//             }
//             hot.loadData(data.nodes)
//         })

//         //currentImage = undefined
//         console.log("Images: "+list_images)
//         hot.loadData(data.nodes);
//         exampleConsole.innerText = 'Data loaded';
//         //var tw = list_images

//     }
// });

// Handsontable.dom.addEvent(refresh, 'click', function(){
//     alert("to implement");
// });

// Handsontable.dom.addEvent(save, 'click', function () {
//     var csvContent = "data:text/csv;charset=utf-8,";
//     var dataToSave = hot.getSourceData()
//     var encodedUri = encodeURIComponent(JSON.stringify(dataToSave))
//     var link = document.createElement("a");
//     link.setAttribute("href", 'data:text/plain;charset=utf-u,' + encodedUri);
//     link.setAttribute("download", "data.json");
//     document.body.appendChild(link);
//     link.click();
//     window.open(encodedUri)
// });

Handsontable.dom.addEvent(autosave, 'click', function () {
    if (autosave.checked) {
        exampleConsole.innerText = 'Changes will be autosaved';
    }
    else {
        exampleConsole.innerText = 'Changes will not be autosaved';
    }
});

<commit_msg>images drop<commit_after>function ajax(url, method, params, callback) {
    var obj;

    try {
        obj = new XMLHttpRequest();
    } catch (e) {
        try {
            obj = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                obj = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("Your browser does not support Ajax.");
                return false;
            }
        }
    }
    obj.onreadystatechange = function () {
        if (obj.readyState == 4) {
            callback(obj);
        }
    };
    obj.open(method, url, true);
    obj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    obj.send(params);

    return obj;
}

var
    $ = function (id) {
        return document.getElementById(id);
    },
    container = $('example1'),
    exampleConsole = $('example1console'),
    autosave = $('autosave'),
    load = $('load'),
    save = $('save'),
    reload = $('reload'),
    autosaveNotification,
    hot,
    number;

hot = new Handsontable(container, {
    startRows: 8,
    startCols: 6,
    columns: [
        { data: "id" },
        { data: "name" },
        { data: "className" },
        { data: "shape" },
        { data: "text" },
        {
            data: "image",
            renderer: coverRenderer,
            type: 'dropdown',
            source: ['http://d279m997dpfwgl.cloudfront.net/wp/2013/03/Asma-Khalid_300.jpg', 'http://img2.zergnet.com/2031933_300.jpg', 'https://i.cbc.ca/1.2115364.1382070777!/httpImage/image.jpg_gen/derivatives/original_300/morton.jpg', 'http://img1.zergnet.com/1391764_300.jpg']
        },
        { data: "image2", renderer: coverRenderer },
        { data: "loaded" },
        {
            data: "style.lineWidth",
            type: 'dropdown',
            source: ['yellow', 'red', 'orange', 'green']
        }, {
            data: "style.radius",
            type: 'dropdown',
            source: ['1px', '2px', '3px']
        }, {
            data: "style.lineColor",
            type: 'dropdown',
            source: ['yellow', 'red', 'orange', 'green']
        }
    ],
    currentRowClassName: 'currentRow',
    rowHeaders: true,
    rowHeights: 60,
    colHeaders: ["ID", "Nombre", "ClassName", "Figura", "Descripción", "Imagen", "Imagen2", "Cargado", "Longitud linea", "Radio", "Color de línea"],
    colWidths: [70, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
    minSpareRows: 1,
    width: 600,
    height: 400,
    persistentState: true,
    contextMenu: true,
    afterChange: function (change, source) {
        if (source === 'loadData') {
            return; //don't save this change
        }
        if (!autosave.checked) {
            return;
        }
        clearTimeout(autosaveNotification);
        ajax('json/save.json', 'GET', JSON.stringify({ data: change }), function (data) {
            exampleConsole.innerText = 'Autosaved (' + change.length + ' ' + 'cell' + (change.length > 1 ? 's' : '') + ')';
            autosaveNotification = setTimeout(function () {
                exampleConsole.innerText = 'Changes will be autosaved';
            }, 1000);
        });
    }
});

hot.updateSettings({
    contextMenu: {
        callback: function (key, options) {
            if (key === 'edit') {
                number = (hot.getSelected()[0]);
                document.getElementById("dialog-with-list-activation").disabled = false;
                (function () {
                    var dialogScrollable = new mdc.dialog.MDCDialog(document.querySelector('#mdc-dialog-with-list'));
                    document.querySelector('#dialog-with-list-activation').addEventListener('click', function (evt) {
                        dialogScrollable.lastFocusedTarget = evt.target;
                        dialogScrollable.show();
                    });
                })();
                (function () {
                    // Hack to work around style-loader async loading styles
                    setTimeout(function () {
                        mdc.ripple.MDCRipple.attachTo(document.querySelector('#dialog-with-list-activation'));
                    }, 200);
                })();
                //document.getElementById("dialog-with-list-activation").disabled = true;
            }
        },
        items: {
            'row_above': {
                name: "Insertar fila encima"
            }, 'row_below': { name: "Insertar debajo" }, 'remove_row': { name: "Eliminar fila" },
            "edit": {
                name: 'Habilitar edición',
                //isHtmlName: true,
                disabled: function () {
                    // if first row, disable this option
                    return !(hot.getSelected()[0, 2, 0, 3] === 0)
                }
            }
        }
    }
})

function coverRenderer(instance, td, row, col, prop, value, cellProperties) {
    var escaped = Handsontable.helper.stringify(value),
        img;

    if (escaped.indexOf('http') === 0 || escaped.indexOf('data:image') === 0) {
        img = document.createElement('IMG');
        img.src = value;
        img.setAttribute('style', 'border-radius: 50%')
        img.setAttribute('width', '50px')
        img.setAttribute('heigth', '50px')

        Handsontable.dom.addEvent(img, 'mousedown', function (e) {
            e.preventDefault(); // prevent selection quirk
        });

        Handsontable.dom.empty(td);
        td.appendChild(img);
    }
    else {
        // render as text
        Handsontable.renderers.TextRenderer.apply(this, arguments);
    }

    return td;
}

// Handsontable.dom.addEvent(load, 'click', function () {
//     var input, file, fr, list_images = {}, dataTotal, data;

//     if (typeof window.FileReader !== 'function') {
//         alert("The file API isn't supported on this browser yet.");
//         return;
//     }

//     input = document.getElementById('fileinput');
//     if (!input) {
//         alert("Um, couldn't find the fileinput element.");
//     }
//     else if (!input.files) {
//         alert("This browser doesn't seem to support the `files` property of file inputs.");
//     }
//     else if (!input.files[0]) {
//         alert("Por favor, selecciona un archivo.");
//     }
//     else {
//         file = input.files[0];
//         fr = new FileReader();
//         fr.onload = receivedText;
//         fr.readAsText(file);
//     }

//     function receivedText(e) {
//         lines = e.target.result;
//         dataTotal = JSON.parse("{ \"data\":" + lines + "}");
//         data = dataTotal.data;
//         console.log("NODES: "+ data.nodes)

//         $('#accept').on('click', function () {
//             if (currentImage != undefined) {
//                 document.getElementById("crop").src = currentImage
//                 list_images[number] = currentImage
//                 for (var n in list_images) {
//                     data.nodes[n].image = list_images[n]
//                 }
//             }
//             hot.loadData(data.nodes)
//         })

//         //currentImage = undefined
//         console.log("Images: "+list_images)
//         hot.loadData(data.nodes);
//         exampleConsole.innerText = 'Data loaded';
//         //var tw = list_images

//     }
// });

// Handsontable.dom.addEvent(refresh, 'click', function(){
//     alert("to implement");
// });

// Handsontable.dom.addEvent(save, 'click', function () {
//     var csvContent = "data:text/csv;charset=utf-8,";
//     var dataToSave = hot.getSourceData()
//     var encodedUri = encodeURIComponent(JSON.stringify(dataToSave))
//     var link = document.createElement("a");
//     link.setAttribute("href", 'data:text/plain;charset=utf-u,' + encodedUri);
//     link.setAttribute("download", "data.json");
//     document.body.appendChild(link);
//     link.click();
//     window.open(encodedUri)
// });

Handsontable.dom.addEvent(autosave, 'click', function () {
    if (autosave.checked) {
        exampleConsole.innerText = 'Changes will be autosaved';
    }
    else {
        exampleConsole.innerText = 'Changes will not be autosaved';
    }
});

<|endoftext|>


<commit_before>(function () {
    var progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
    var importRegEx = /((?:xaml!)?[a-z]+(\.[a-z]+[a-z0-9]*)*)/mgi;

    define(function () {

        if (!Array.prototype.indexOf) {
            Array.prototype.indexOf = function (obj) {
                for (var i = 0; i < this.length; i++) {
                    if (this[i] == obj) {
                        return i;
                    }
                }
                return -1;
            }
        }

        /**
         * IE8 FIXES
         * @param domNode
         */
        var localNameFromDomNode = function(domNode){
            if(domNode.localName) return domNode.localName;

            var st = domNode.tagName.split(":");
            return st[st.length-1];
        };

        return {
            version: '0.1.0',

            createXhr: function () {
                var xhr, i, progId;
                if (typeof XMLHttpRequest !== "undefined") {
                    return new XMLHttpRequest();
                } else {
                    for (i = 0; i < 3; i++) {
                        progId = progIds[i];
                        try {
                            xhr = new ActiveXObject(progId);
                        } catch (e) {
                        }

                        if (xhr) {
                            progIds = [progId];  // so faster next time
                            break;
                        }
                    }
                }

                if (!xhr) {
                    throw new Error("createXhr(): XMLHttpRequest not available");
                }

                return xhr;
            },

            get: function (url, callback) {
                var xhr;
                try {
                    xhr = this.createXhr();

                    xhr.open('GET', url, true);

                    xhr.onreadystatechange = function (evt) {
                        //Do not explicitly handle errors, those should be
                        //visible via console output in the browser.
                        if (xhr.readyState === 4) {
                            callback(null, xhr);
                        }
                    };
                    xhr.send(null);

                } catch (e) {
                    callback(e);
                }

            },

            getDependency: function(namespace, localName, namespaceMap, xamlClasses, rewriteMap) {
                var fqClassName = [namespaceMap[namespace] || namespace, localName].join(".");

                for (var i = 0; i < rewriteMap.length; i++) {
                    var entry = rewriteMap[i];
                    if (entry.$from && entry.$to) {
                        if (entry.$from.test(fqClassName)) {
                            fqClassName = fqClassName.replace(entry.$from, entry.$to);

                            break;
                        }
                    }
                }

                // TODO fix
                if (xamlClasses.indexOf(fqClassName) != -1) {
                    fqClassName = "xaml!" + fqClassName;
                }

                return fqClassName.replace(/\./g, "/");
            },

            findDependencies: function (xaml, namespaceMap, xamlClasses, rewriteMap, imports) {

                var self = this;
                var ret = [];

                function findDependencies(domNode) {

                    var localName = localNameFromDomNode(domNode);

                    var dep = self.getDependency(domNode.namespaceURI, localName, namespaceMap, xamlClasses, rewriteMap);
                    // console.log(dep);
                    if (dep == "js/core/Imports") {
                        for (var t = 0; t < domNode.childNodes.length; t++) {
                            var importNode = domNode.childNodes[t];
                            if (importNode.nodeType == 3) {
                                // text node
                                var m;
                                var textContent = importNode.textContent ? importNode.textContent : importNode.text;
                                while ((m = importRegEx.exec(textContent+" ")) != null) {
                                    var importClass =  m[0].replace(/\./g, "/");
                                    if(importClass !== "undefined"){
                                        if (ret.indexOf(importClass) == -1) {
                                            ret.push(importClass);
                                        }

                                        if (imports) {
                                            imports.push(importClass);
                                        }
                                    }

                                }
                            }
                        }
                    }

                    if (ret.indexOf(dep) == -1) {
                        ret.push(dep);
                    }

                    for (var i = 0; i < domNode.childNodes.length; i++) {
                        var childNode = domNode.childNodes[i];

                        // element
                        if (childNode.nodeType == 1) {
                            findDependencies(childNode);
                        }
                    }

                }

                if (xaml) {
                    findDependencies(xaml);
                }

                return ret;
            },

            findScripts: function(xaml, namespaceMap, xamlClasses, rewriteMap) {
                var ret = [];

                for (var i = 0; i < xaml.childNodes.length; i++) {
                    var node = xaml.childNodes[i];
                    if (node.nodeType == 1) {
                        if ("js/core/Script" == this.getDependency(node.namespaceURI, localNameFromDomNode(node), namespaceMap, xamlClasses, rewriteMap)) {
                            ret.push(node);
                        }
                    }
                }

                return ret;
            },

            getDeclarationFromScripts: function(scripts) {
                var ret = {};

                if (scripts) {
                    for (var s = 0; s < scripts.length; s++) {
                        var script = scripts[s];
                        for (var fn in script) {
                            if (script.hasOwnProperty(fn)) {
                                ret[fn] = script[fn];
                            }
                        }
                    }
                }

                return ret;
            },

            load: function (name, req, onLoad, config) {
//                if (config.isBuild && !config.inlineText) {
//                    onLoad();
//                    return;
//                }
                var self = this;
                var url = req.toUrl(name.replace(/\./g, "/") + ".xml");
                this.get(url, function (err, xhr) {
                    if (!err) {
                        if (xhr.responseXML) {
                            // require all dependencies
                            var imports = [];

                            var dependencies = self.findDependencies(xhr.responseXML.documentElement,
                                config.namespaceMap, config.xamlClasses, config.rewriteMap, imports);
                            for (var i = 0; i < imports.length; i++) {
                                // console.log(imports[i]);
                            }
                            var scripts = self.findScripts(xhr.responseXML.documentElement,
                                config.namespaceMap, config.xamlClasses, config.rewriteMap);

                            if (scripts.length > 0) {
                                // at least one script

                                dependencies.splice(1, 0, "js/core/Script");
                            }

                            if(imports.length > 0){
                                dependencies = dependencies.concat(imports);
                            }
                            for(i = 0 ; i < dependencies.length; i++){
                               // console.log("AFTER: "+dependencies[i]);
                            }

                            // first item should be the dependency of the document element
                            req(dependencies, function() {
                                // dependencies are loaded
                                var baseClass = arguments[0],
                                    Script = arguments[1];

                                var args = [];
                                for(var i = 1; i < arguments.length; i++){
                                    args.push(arguments[i]);
                                }

                                var scriptObjects = [];
                                var importedClasses = args.slice(args.length - imports.length);

                                if (scripts.length > 0) {
                                    for (var s = 0; s < scripts.length; s++) {
                                        try {

                                            var scriptInstance = new Script(null, scripts[s]);
                                            scriptObjects.push(scriptInstance.evaluate(importedClasses));
                                        } catch (e) {
                                            throw "Script cannot be loaded";
                                        }
                                    }
                                }

                                var xamlFactory = baseClass.inherit(
                                    self.getDeclarationFromScripts(scriptObjects)
                                );

                                xamlFactory.prototype._$descriptor = xhr.responseXML.documentElement;

                                if (config.applicationDomain) {
                                    config.applicationDomain.defineXamlClass(name, dependencies, xamlFactory);
                                    onLoad(xamlFactory);
                                }

                            });

                        } else {
                            throw name + " wasn't a valid xml document";
                        }
                    } else {
                        throw err;
                    }
                });
            }
        };

    });
})();<commit_msg>removed debug output from xaml plugin<commit_after>(function () {
    var progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
    var importRegEx = /((?:xaml!)?[a-z]+(\.[a-z]+[a-z0-9]*)*)/mgi;

    define(function () {

        if (!Array.prototype.indexOf) {
            Array.prototype.indexOf = function (obj) {
                for (var i = 0; i < this.length; i++) {
                    if (this[i] == obj) {
                        return i;
                    }
                }
                return -1;
            }
        }

        /**
         * IE8 FIXES
         * @param domNode
         */
        var localNameFromDomNode = function(domNode){
            if(domNode.localName) return domNode.localName;

            var st = domNode.tagName.split(":");
            return st[st.length-1];
        };

        return {
            version: '0.1.0',

            createXhr: function () {
                var xhr, i, progId;
                if (typeof XMLHttpRequest !== "undefined") {
                    return new XMLHttpRequest();
                } else {
                    for (i = 0; i < 3; i++) {
                        progId = progIds[i];
                        try {
                            xhr = new ActiveXObject(progId);
                        } catch (e) {
                        }

                        if (xhr) {
                            progIds = [progId];  // so faster next time
                            break;
                        }
                    }
                }

                if (!xhr) {
                    throw new Error("createXhr(): XMLHttpRequest not available");
                }

                return xhr;
            },

            get: function (url, callback) {
                var xhr;
                try {
                    xhr = this.createXhr();

                    xhr.open('GET', url, true);

                    xhr.onreadystatechange = function (evt) {
                        //Do not explicitly handle errors, those should be
                        //visible via console output in the browser.
                        if (xhr.readyState === 4) {
                            callback(null, xhr);
                        }
                    };
                    xhr.send(null);

                } catch (e) {
                    callback(e);
                }

            },

            getDependency: function(namespace, localName, namespaceMap, xamlClasses, rewriteMap) {
                var fqClassName = [namespaceMap[namespace] || namespace, localName].join(".");

                for (var i = 0; i < rewriteMap.length; i++) {
                    var entry = rewriteMap[i];
                    if (entry.$from && entry.$to) {
                        if (entry.$from.test(fqClassName)) {
                            fqClassName = fqClassName.replace(entry.$from, entry.$to);

                            break;
                        }
                    }
                }

                // TODO fix
                if (xamlClasses.indexOf(fqClassName) != -1) {
                    fqClassName = "xaml!" + fqClassName;
                }

                return fqClassName.replace(/\./g, "/");
            },

            findDependencies: function (xaml, namespaceMap, xamlClasses, rewriteMap, imports) {

                var self = this;
                var ret = [];

                function findDependencies(domNode) {

                    var localName = localNameFromDomNode(domNode);

                    var dep = self.getDependency(domNode.namespaceURI, localName, namespaceMap, xamlClasses, rewriteMap);
                    // console.log(dep);
                    if (dep == "js/core/Imports") {
                        for (var t = 0; t < domNode.childNodes.length; t++) {
                            var importNode = domNode.childNodes[t];
                            if (importNode.nodeType == 3) {
                                // text node
                                var m;
                                var textContent = importNode.textContent ? importNode.textContent : importNode.text;
                                while ((m = importRegEx.exec(textContent+" ")) != null) {
                                    var importClass =  m[0].replace(/\./g, "/");
                                    if(importClass !== "undefined"){
                                        if (ret.indexOf(importClass) == -1) {
                                            ret.push(importClass);
                                        }

                                        if (imports) {
                                            imports.push(importClass);
                                        }
                                    }

                                }
                            }
                        }
                    }

                    if (ret.indexOf(dep) == -1) {
                        ret.push(dep);
                    }

                    for (var i = 0; i < domNode.childNodes.length; i++) {
                        var childNode = domNode.childNodes[i];

                        // element
                        if (childNode.nodeType == 1) {
                            findDependencies(childNode);
                        }
                    }

                }

                if (xaml) {
                    findDependencies(xaml);
                }

                return ret;
            },

            findScripts: function(xaml, namespaceMap, xamlClasses, rewriteMap) {
                var ret = [];

                for (var i = 0; i < xaml.childNodes.length; i++) {
                    var node = xaml.childNodes[i];
                    if (node.nodeType == 1) {
                        if ("js/core/Script" == this.getDependency(node.namespaceURI, localNameFromDomNode(node), namespaceMap, xamlClasses, rewriteMap)) {
                            ret.push(node);
                        }
                    }
                }

                return ret;
            },

            getDeclarationFromScripts: function(scripts) {
                var ret = {};

                if (scripts) {
                    for (var s = 0; s < scripts.length; s++) {
                        var script = scripts[s];
                        for (var fn in script) {
                            if (script.hasOwnProperty(fn)) {
                                ret[fn] = script[fn];
                            }
                        }
                    }
                }

                return ret;
            },

            load: function (name, req, onLoad, config) {

                var self = this;
                var url = req.toUrl(name.replace(/\./g, "/") + ".xml");
                this.get(url, function (err, xhr) {
                    if (!err) {
                        if (xhr.responseXML) {
                            // require all dependencies
                            var imports = [];

                            var dependencies = self.findDependencies(xhr.responseXML.documentElement,
                                config.namespaceMap, config.xamlClasses, config.rewriteMap, imports);

                            var scripts = self.findScripts(xhr.responseXML.documentElement,
                                config.namespaceMap, config.xamlClasses, config.rewriteMap);

                            if (scripts.length > 0) {
                                // at least one script

                                dependencies.splice(1, 0, "js/core/Script");
                            }

                            if(imports.length > 0){
                                dependencies = dependencies.concat(imports);
                            }

                            // first item should be the dependency of the document element
                            req(dependencies, function() {
                                // dependencies are loaded
                                var baseClass = arguments[0],
                                    Script = arguments[1];

                                var args = [];
                                for(var i = 1; i < arguments.length; i++){
                                    args.push(arguments[i]);
                                }

                                var scriptObjects = [];
                                var importedClasses = args.slice(args.length - imports.length);

                                if (scripts.length > 0) {
                                    for (var s = 0; s < scripts.length; s++) {
                                        try {

                                            var scriptInstance = new Script(null, scripts[s]);
                                            scriptObjects.push(scriptInstance.evaluate(importedClasses));
                                        } catch (e) {
                                            throw "Script cannot be loaded";
                                        }
                                    }
                                }

                                var xamlFactory = baseClass.inherit(
                                    self.getDeclarationFromScripts(scriptObjects)
                                );

                                xamlFactory.prototype._$descriptor = xhr.responseXML.documentElement;

                                if (config.applicationDomain) {
                                    config.applicationDomain.defineXamlClass(name, dependencies, xamlFactory);
                                    onLoad(xamlFactory);
                                }

                            });

                        } else {
                            throw name + " wasn't a valid xml document";
                        }
                    } else {
                        throw err;
                    }
                });
            }
        };

    });
})();<|endoftext|>


<commit_before>game.PlayScreen = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		// reset the score
		game.data.score = 0;
                me.levelDirector.loadLevel("level01");

                var player = me.pool.pull("player", 0, 420, {});
                me.game.world.addChild(player, 5);

		// add our HUD to the game world
		this.HUD = new game.HUD.Container();
		me.game.world.addChild(this.HUD);
	},

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {
		// remove the HUD from the game world
		me.game.world.removeChild(this.HUD);
	}
});
<commit_msg>finished video 7<commit_after>game.PlayScreen = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		// reset the score
		game.data.score = 0;
                me.levelDirector.loadLevel("level01");

                var player = me.pool.pull("player", 0, 420, {});
                me.game.world.addChild(player, 5);

                me.input.bindKey

		// add our HUD to the game world
		this.HUD = new game.HUD.Container();
		me.game.world.addChild(this.HUD);
	},

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {
		// remove the HUD from the game world
		me.game.world.removeChild(this.HUD);
	}
});
<|endoftext|>


<commit_before>(function () {
    var SimpleCookie = {};

    SimpleCookie.save = function (data, options) {
        options = options || {};
        options.path = options.path || '/';

        var cookie = [data.key, '=', JSON.stringify(data.value), '; domain=.', window.location.hostname, '; path=', options.path, ';'].join('');
        document.cookie;
    };

    SimpleCookie.get = function (key) {
        return document.cookie.match(new RegExp(key + '=([^;]+)'));
    };

    SimpleCookie.remove = function (key) {
        var cookie = document.cookie.match(new RegExp(key + '=([^;]+)'));
        return cookie;
    };

    SimpleCookie.parse = function (name) {
        var result = this.get(name);
        return result && (result = JSON.parse(result[1]));
    };

    window.SimpleCookie = SimpleCookie;

}).call(this);
<commit_msg>update variable assignment<commit_after>(function () {
    var SimpleCookie = {};

    SimpleCookie.save = function (data, options) {
        options = options || {};
        options.path = options.path || '/';

        var cookie = [data.key, '=', JSON.stringify(data.value), '; domain=.', window.location.hostname, '; path=', options.path, ';'].join('');
        document.cookie = cookie;
    };

    SimpleCookie.get = function (key) {
        return document.cookie.match(new RegExp(key + '=([^;]+)'));
    };

    SimpleCookie.remove = function (key) {
        var cookie = document.cookie.match(new RegExp(key + '=([^;]+)'));
        return cookie;
    };

    SimpleCookie.parse = function (name) {
        var result = this.get(name);
        return result && (result = JSON.parse(result[1]));
    };

    window.SimpleCookie = SimpleCookie;

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