<commit_before>/* ===========================================================
 * bootstrap-modal.js v2.0
 * ===========================================================
 * Copyright 2012 Jordan Schroter
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

!function ($) {

	"use strict"; // jshint ;_;

	/* MODAL CLASS DEFINITION
	* ====================== */

	var Modal = function (element, options) {
		this.init(element, options);
	}

	Modal.prototype = {

		constructor: Modal,

		init: function (element, options) {
			this.options = options;

			this.$element = $(element)
				.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this));

			this.options.remote && this.$element.find('.modal-body').load(this.options.remote);

			var manager = typeof this.options.manager === 'function' ?
				this.options.manager.call(this) : this.options.manager;

			manager = manager.appendModal ?
				manager : $(manager).modalmanager().data('modalmanager');

			manager.appendModal(this);
		},

		toggle: function () {
			return this[!this.isShown ? 'show' : 'hide']();
		},

		show: function () {
			var that = this,
				e = $.Event('show');

			if (this.isShown) return;

			this.$element.triggerHandler(e);

			if (e.isDefaultPrevented()) return;

			if (this.options.width){
				this.$element.css('width', this.options.width);

				var that = this;
				this.$element.css('margin-left', function () {
					if (/%/ig.test(that.options.width)){
						return -(parseInt(that.options.width) / 2) + '%';
					} else {
						return -($(this).width() / 2) + 'px';
					}
				});
			}

			var prop = this.options.height ? 'height' : 'max-height';

			var value = this.options.height || this.options.maxHeight;

			if (value){
				this.$element.find('.modal-body')
					.css('overflow', 'auto')
					.css(prop, value);
			}

			this.escape();

			this.tab();

			this.options.loading && this.loading();
		},

		hide: function (e) {
			e && e.preventDefault();

			e = $.Event('hide');

			this.$element.triggerHandler(e);

			if (!this.isShown || e.isDefaultPrevented()) return (this.isShown = false);

			this.isShown = false;

			this.escape();

			this.tab();

			this.isLoading && this.loading();

			$(document).off('focusin.modal');

			this.$element
				.removeClass('in')
				.removeClass('animated')
				.removeClass(this.options.attentionAnimation)
				.removeClass('modal-overflow')
				.attr('aria-hidden', true);

			$.support.transition && this.$element.hasClass('fade') ?
				this.hideWithTransition() :
				this.hideModal();
		},

		tab: function () {
			var that = this;

			if (this.isShown && this.options.consumeTab) {
				this.$element.on('keydown.tabindex.modal', '[data-tabindex]', function (e) {
			    	if (e.keyCode && e.keyCode == 9){
				        var $next = $(this),
				        	$rollover = $(this);

				       	that.$element.find('[data-tabindex]:enabled:not([readonly])').each(function (e) {
			         		if (!e.shiftKey){
			           	 		$next = $next.data('tabindex') < $(this).data('tabindex') ?
				              		$next = $(this) :
				              		$rollover = $(this);
				          	} else {
				            	$next = $next.data('tabindex') > $(this).data('tabindex') ?
				              		$next = $(this) :
				             		$rollover = $(this);
				          	}
				        });

				        $next[0] !== $(this)[0] ?
			          		$next.focus() : $rollover.focus();

				        e.preventDefault();

			      	}
			    });
			} else if (!this.isShown) {
				this.$element.off('keydown.tabindex.modal');
			}
		},

		escape: function () {
			var that = this;
			if (this.isShown && this.options.keyboard) {
				if (!this.$element.attr('tabindex')) this.$element.attr('tabindex', -1);

				this.$element.on('keyup.dismiss.modal', function (e) {
					e.which == 27 && that.hide();
				});
			} else if (!this.isShown) {
				this.$element.off('keyup.dismiss.modal')
			}
		},

		hideWithTransition: function () {
			var that = this
				, timeout = setTimeout(function () {
					that.$element.off($.support.transition.end)
					that.hideModal()
				}, 500);

			this.$element.one($.support.transition.end, function () {
				clearTimeout(timeout)
				that.hideModal()
			});
		},

		hideModal: function () {
			this.$element
				.hide()
				.triggerHandler('hidden');

			var prop = this.options.height ? 'height' : 'max-height';
			var value = this.options.height || this.options.maxHeight;

			if (value){
				this.$element.find('.modal-body')
					.css('overflow', '')
					.css(prop, '');
			}

		},

		removeLoading: function () {
			this.$loading.remove();
			this.$loading = null;
			this.isLoading = false;
		},

		loading: function (callback) {
			callback = callback || function () {};

			var animate = this.$element.hasClass('fade') ? 'fade' : '';

			if (!this.isLoading) {
				var doAnimate = $.support.transition && animate;

				this.$loading = $('
')
					.append(this.options.spinner)
					.appendTo(this.$element);

				if (doAnimate) this.$loading[0].offsetWidth // force reflow

				this.$loading.addClass('in')

				this.isLoading = true;

				doAnimate ?
					this.$loading.one($.support.transition.end, callback) :
					callback();

			} else if (this.isLoading && this.$loading) {
				this.$loading.removeClass('in');

				var that = this;
				$.support.transition && this.$element.hasClass('fade')?
					this.$loading.one($.support.transition.end, function () { that.removeLoading() }) :
					that.removeLoading();

			} else if (callback) {
				callback(this.isLoading);
			}
		},

		focus: function () {
			var $focusElem = this.$element.find(this.options.focusOn);

			$focusElem = $focusElem.length ? $focusElem : this.$element;

			$focusElem.focus();
		},

		attention: function (){
			// NOTE: transitionEnd with keyframes causes odd behaviour

			if (this.options.attentionAnimation){
				this.$element
					.removeClass('animated')
					.removeClass(this.options.attentionAnimation);

				var that = this;

				setTimeout(function () {
					that.$element
						.addClass('animated')
						.addClass(that.options.attentionAnimation);
				}, 0);
			}

			this.focus();
		},

		destroy: function () {
			var e = $.Event('destroy');
			this.$element.triggerHandler(e);
			if (e.isDefaultPrevented()) return;

			this.teardown();
		},

		teardown: function () {
			if (!this.$parent.length){
				this.$element.remove();
				this.$element = null;
			} else {
				this.$element.appendTo(this.$parent);
			}

			this.$element.off('.modal');
			this.$element.removeData('modal');
			this.$element
				.removeClass('in')
				.attr('aria-hidden', true);
		}
	}

	/* MODAL PLUGIN DEFINITION
	* ======================= */

	$.fn.modal = function (option) {
		return this.each(function () {
			var $this = $(this),
				data = $this.data('modal'),
				options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option);

			if (!data) $this.data('modal', (data = new Modal(this, options)))
			if (typeof option == 'string') data[option]()
			else if (options.show) data.show()
		})
	}

	$.fn.modal.defaults = {
		keyboard: true,
		backdrop: true,
		loading: false,
		show: true,
		width: null,
		height: null,
		maxHeight: null,
		modalOverflow: false,
		consumeTab: true,
		focusOn: null,
		attentionAnimation: 'shake',
		manager: 'body',
		spinner: '

'
	}

	$.fn.modal.Constructor = Modal

	/* MODAL DATA-API
	* ============== */

	$(function () {
		$(document).off('.modal').on('click.modal.data-api', '[data-toggle="modal"]', function ( e ) {
			var $this = $(this),
				href = $this.attr('href'),
				$target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))), //strip for ie7
				option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data());

			e.preventDefault();
			$target
				.modal(option)
				.one('hide', function () {
					$this.focus();
				})
		});
	});

}(window.jQuery);<commit_msg>fixed modals not disposing properly<commit_after>/* ===========================================================
 * bootstrap-modal.js v2.0
 * ===========================================================
 * Copyright 2012 Jordan Schroter
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

!function ($) {

	"use strict"; // jshint ;_;

	/* MODAL CLASS DEFINITION
	* ====================== */

	var Modal = function (element, options) {
		this.init(element, options);
	}

	Modal.prototype = {

		constructor: Modal,

		init: function (element, options) {
			this.options = options;

			this.$element = $(element)
				.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this));

			this.options.remote && this.$element.find('.modal-body').load(this.options.remote);

			var manager = typeof this.options.manager === 'function' ?
				this.options.manager.call(this) : this.options.manager;

			manager = manager.appendModal ?
				manager : $(manager).modalmanager().data('modalmanager');

			manager.appendModal(this);
		},

		toggle: function () {
			return this[!this.isShown ? 'show' : 'hide']();
		},

		show: function () {
			var that = this,
				e = $.Event('show');

			if (this.isShown) return;

			this.$element.triggerHandler(e);

			if (e.isDefaultPrevented()) return;

			if (this.options.width){
				this.$element.css('width', this.options.width);

				var that = this;
				this.$element.css('margin-left', function () {
					if (/%/ig.test(that.options.width)){
						return -(parseInt(that.options.width) / 2) + '%';
					} else {
						return -($(this).width() / 2) + 'px';
					}
				});
			}

			var prop = this.options.height ? 'height' : 'max-height';

			var value = this.options.height || this.options.maxHeight;

			if (value){
				this.$element.find('.modal-body')
					.css('overflow', 'auto')
					.css(prop, value);
			}

			this.escape();

			this.tab();

			this.options.loading && this.loading();
		},

		hide: function (e) {
			e && e.preventDefault();

			e = $.Event('hide');

			this.$element.triggerHandler(e);

			if (!this.isShown || e.isDefaultPrevented()) return (this.isShown = false);

			this.isShown = false;

			this.escape();

			this.tab();

			this.isLoading && this.loading();

			$(document).off('focusin.modal');

			this.$element
				.removeClass('in')
				.removeClass('animated')
				.removeClass(this.options.attentionAnimation)
				.removeClass('modal-overflow')
				.attr('aria-hidden', true);

			$.support.transition && this.$element.hasClass('fade') ?
				this.hideWithTransition() :
				this.hideModal();
		},

		tab: function () {
			var that = this;

			if (this.isShown && this.options.consumeTab) {
				this.$element.on('keydown.tabindex.modal', '[data-tabindex]', function (e) {
			    	if (e.keyCode && e.keyCode == 9){
				        var $next = $(this),
				        	$rollover = $(this);

				       	that.$element.find('[data-tabindex]:enabled:not([readonly])').each(function (e) {
			         		if (!e.shiftKey){
			           	 		$next = $next.data('tabindex') < $(this).data('tabindex') ?
				              		$next = $(this) :
				              		$rollover = $(this);
				          	} else {
				            	$next = $next.data('tabindex') > $(this).data('tabindex') ?
				              		$next = $(this) :
				             		$rollover = $(this);
				          	}
				        });

				        $next[0] !== $(this)[0] ?
			          		$next.focus() : $rollover.focus();

				        e.preventDefault();

			      	}
			    });
			} else if (!this.isShown) {
				this.$element.off('keydown.tabindex.modal');
			}
		},

		escape: function () {
			var that = this;
			if (this.isShown && this.options.keyboard) {
				if (!this.$element.attr('tabindex')) this.$element.attr('tabindex', -1);

				this.$element.on('keyup.dismiss.modal', function (e) {
					e.which == 27 && that.hide();
				});
			} else if (!this.isShown) {
				this.$element.off('keyup.dismiss.modal')
			}
		},

		hideWithTransition: function () {
			var that = this
				, timeout = setTimeout(function () {
					that.$element.off($.support.transition.end)
					that.hideModal()
				}, 500);

			this.$element.one($.support.transition.end, function () {
				clearTimeout(timeout)
				that.hideModal()
			});
		},

		hideModal: function () {
			this.$element
				.hide()
				.triggerHandler('hidden');

			var prop = this.options.height ? 'height' : 'max-height';
			var value = this.options.height || this.options.maxHeight;

			if (value){
				this.$element.find('.modal-body')
					.css('overflow', '')
					.css(prop, '');
			}

		},

		removeLoading: function () {
			this.$loading.remove();
			this.$loading = null;
			this.isLoading = false;
		},

		loading: function (callback) {
			callback = callback || function () {};

			var animate = this.$element.hasClass('fade') ? 'fade' : '';

			if (!this.isLoading) {
				var doAnimate = $.support.transition && animate;

				this.$loading = $('
')
					.append(this.options.spinner)
					.appendTo(this.$element);

				if (doAnimate) this.$loading[0].offsetWidth // force reflow

				this.$loading.addClass('in')

				this.isLoading = true;

				doAnimate ?
					this.$loading.one($.support.transition.end, callback) :
					callback();

			} else if (this.isLoading && this.$loading) {
				this.$loading.removeClass('in');

				var that = this;
				$.support.transition && this.$element.hasClass('fade')?
					this.$loading.one($.support.transition.end, function () { that.removeLoading() }) :
					that.removeLoading();

			} else if (callback) {
				callback(this.isLoading);
			}
		},

		focus: function () {
			var $focusElem = this.$element.find(this.options.focusOn);

			$focusElem = $focusElem.length ? $focusElem : this.$element;

			$focusElem.focus();
		},

		attention: function (){
			// NOTE: transitionEnd with keyframes causes odd behaviour

			if (this.options.attentionAnimation){
				this.$element
					.removeClass('animated')
					.removeClass(this.options.attentionAnimation);

				var that = this;

				setTimeout(function () {
					that.$element
						.addClass('animated')
						.addClass(that.options.attentionAnimation);
				}, 0);
			}

			this.focus();
		},

		destroy: function () {
			var e = $.Event('destroy');
			this.$element.triggerHandler(e);
			if (e.isDefaultPrevented()) return;

			this.teardown();
		},

		teardown: function () {
			if (!this.$parent.length){
				this.$element.remove();
				this.$element = null;
				return;
			}

			if (this.$parent !== this.$element.parent()){
				this.$element.appendTo(this.$parent);
			}

			this.$element.off('.modal');
			this.$element.removeData('modal');
			this.$element
				.removeClass('in')
				.attr('aria-hidden', true);
		}
	}

	/* MODAL PLUGIN DEFINITION
	* ======================= */

	$.fn.modal = function (option) {
		return this.each(function () {
			var $this = $(this),
				data = $this.data('modal'),
				options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option);

			if (!data) $this.data('modal', (data = new Modal(this, options)))
			if (typeof option == 'string') data[option]()
			else if (options.show) data.show()
		})
	}

	$.fn.modal.defaults = {
		keyboard: true,
		backdrop: true,
		loading: false,
		show: true,
		width: null,
		height: null,
		maxHeight: null,
		modalOverflow: false,
		consumeTab: true,
		focusOn: null,
		attentionAnimation: 'shake',
		manager: 'body',
		spinner: '

'
	}

	$.fn.modal.Constructor = Modal

	/* MODAL DATA-API
	* ============== */

	$(function () {
		$(document).off('.modal').on('click.modal.data-api', '[data-toggle="modal"]', function ( e ) {
			var $this = $(this),
				href = $this.attr('href'),
				$target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))), //strip for ie7
				option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data());

			e.preventDefault();
			$target
				.modal(option)
				.one('hide', function () {
					$this.focus();
				})
		});
	});

}(window.jQuery);<|endoftext|>


<commit_before>// Author: Rok Garbas
// Contact: rok@garbas.si
// Version: 1.0
//
// Description:
//    plone.toolbar.js script makes sure that all dropdowns in Plone's toolbar
//    are in sync with iframe's stretching/schrinking.
//
// License:
//
// Copyright (C) 2010 Plone Foundation
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

if (window.jQuery) {
  define( "jquery", [], function () {
    "use strict";
    return window.jQuery;
  } );
}

define([
  'jquery',
  'mockup-router',
  'mockup-iframe',
  'mockup-registry',
  'mockup-patterns-toggle',
  'mockup-patterns-modal',
  'mockup-patterns-tinymce',
  'mockup-patterns-structure',
  'mockup-bundles-widgets'
], function($, Router, iframe, registry, Toggle, Modal, TinyMCE, Structure) {
  "use strict";

  // BBB: we need to hook pattern to classes which plone was using until now
  var Toolbar = {
    name: "plone-toolbar",
    transform: function($root) {
      if ($root.hasClass('modal')) {
        /* do not run in modal */
        return;
      }

      // Dropdown {{{

      // toggle class on click (shows dropdown)
      $('.toolbar-dropdown > a').each(function() {
        $(this).patternToggle({
          target: '.toolbar-dropdown',
          value: 'toolbar-dropdown-open',
          menu: 'parent'
        });
      });

      // make sure clicking on anything in the menu closes the toggled element
      $('.toolbar-dropdown .toolbar-dropdown-menu a').click(function(e) {
          $(this).parents('.toolbar-dropdown').children('a').trigger('click');
      });

      // at opening toolbar dropdown:
      // - close all other opened dropdown buttons
      // - stretch iframe
      // at closing dropdown shrink iframe
      $(document)
        .on('add-attr.toggle.patterns', '.toolbar-dropdown > a', function(e) {
          var $el = $(this);
          $('.toolbar-dropdown-open > a').each(function() {
            if ($el[0] !== $(this)[0]) {
              $(this).trigger('click');
            }
          });
          iframe.stretch();
        })
        .on('removed-attr.toggle.patterns', '.toolbar-dropdown > a', function(e) {
          iframe.shrink();
        });

      // }}}

      // Modals Helpers {{{

      // make sure we close all dropdowns when iframe is shrinking
      iframe.$el.on('shrink.iframe', function(e) {
        $('.toolbar-dropdown-open > a').each(function() {
          $(this).trigger('click');
        });
      });

      // integration of toolbar and modals
      $(document)
        .on('before-ajax.modal.patterns', 'a.modal-trigger, a.pat-modal', function(e) {
          var $el = $(this);
          $('.toolbar-dropdown-open > a').each(function() {
            if ($el[0] !== $(this)[0]) {
              $(this).trigger('click');
            }
          });
          $('body', iframe.document).css('overflow', 'hidden');
          iframe.stretch();
        })
        .on('show.modal.patterns', 'a.modal-trigger, a.pat-modal', function(e, modal) {
          var $el = $(this);
          $('.toolbar-dropdown-open > a').each(function() {
            if ($el[0] !== $(this)[0]) {
              $(this).trigger('click');
            }
          });
          $('body', iframe.document).css('overflow', 'hidden');
          iframe.stretch();
        })
        .on('hidden.modal.patterns', 'a.modal-trigger, a.pat-modal', function(e) {
          $('body', iframe.document).css('overflow', 'visible');
          iframe.shrink();
        });

      // }}}

      // Modals {{{

      // Contents
      $('#plone-action-folderContents > a').addClass('modal-trigger').patternModal({
        width: '90%',
        actionOptions: {
          onSuccess: function(modal, response, state, xhr, form){
          }
        }
      });

      // site setup
      $('#plone-sitesetup a').addClass('modal-trigger').patternModal({
        width: '80%',
        loadLinksWithinModal: false,
        actionOptions: {
          displayInModal: false
        }
      }).on('show.modal.patterns', function(evt, modal) {
        $('a[href]', modal.$modal).each(function(){
          var href = this.href;
          var parts = href.split('/');
          parts.splice(parts.length-1, 0, '++nodiazo++');
          href = parts.join('/');

          $(this).attr('href', href);
          $(this).click(function(){
            window.open(href);
          });
        });
      });

      // Manage portlets
      var portletOptions = {
        width: '50%',
        buttons: '.formControls > input[type="submit"],.actionButtons input[type="submit"]',
        automaticallyAddButtonActions: false
      };
      $('#toolbar-manage-portlets a,#manage-dashboard a')
      .addClass('pat-modal')
      .attr('data-pat-modal', JSON.stringify(portletOptions))
      .on('render.modal.patterns', function(e, modal) {
        // Kill the onchange method so we can wire up our own
        $('.section select', modal.$raw).removeAttr('onchange');
        modal.options.actions = {
            // Handle adding portlets via the select
            '.section select': {
              eventType: 'change',
              onSuccess: function(modal, response, state, xhr, form) {
                  if (modal.$modal.find('.pat-modal-buttons input').length === 0) {
                      // The portlet didn't have an edit form (e.g. calendar)
                      modal.reloadWindow();
                  }
              },
              ajaxUrl: function($action, options) {
                var portlet = $action.val();
                var form_action = $action.parents('form').attr('action');
                return form_action + portlet;
              }
            },
            '.actionButtons input': {
              // Handle errors on portlet submission
              error: '.fieldErrorBox',
              onSuccess: function(modal, response, state, xhr, form) {
                modal.reloadWindow();
              }
            },
            // Handle moving and hiding portlets
            '.portlet-action': {
              isForm: true
            }
          };
      })
      .on('hidden.modal.patterns', function(e, modal) {
          modal.reloadWindow();
        }
      );

      // Edit/Add
      $('#plone-contentmenu-factories ul li').addClass('is-content');
      $('#plone-contentmenu-factories ul li#plone-contentmenu-more').removeClass('is-content');
      $('#plone-contentmenu-factories ul li#plone-contentmenu-settings').removeClass('is-content');
      var editOptions = {
        width: '80%',
        backdropOptions: {
          closeOnClick: false
        },
        content: '#content',
        automaticallyAddButtonActions: false,
        actionOptions: {
          displayInModal: false
        },
        actions: {
          'input#form-buttons-save, .formControls input[name="form.button.save"]': {},
          'input#form-buttons-cancel, .formControls input[name="form.button.cancel"]': {
            modalFunction: 'hide'
          }
        },
        routerOptions: {
          id: 'edit',
          pathExp: '/edit$'
        }
      };
      var addOptions = editOptions;

      addOptions.actionOptions.redirectOnResponse = true;
      $('#plone-action-edit > a, #plone-contentmenu-factories ul li.is-content a')
        .addClass('pat-modal')
        .attr('data-pat-modal', JSON.stringify(editOptions));

      delete addOptions.routerOptions;
      $('#plone-contentmenu-factories ul li.is-content a')
        .addClass('pat-modal')
        .attr('data-pat-modal', JSON.stringify(addOptions));

      // Content Rules
      var rulesOptions = {
        width: '80%',
        content: '#content-core',
        loadLinksWithinModal: false
      };
      $('#plone-action-contentrules > a')
        .addClass('pat-modal')
        .attr('data-pat-modal', JSON.stringify(rulesOptions)).
        on('render.modal.patterns', function(e, modal) {
          modal.options.actions = {
            'table.listing a': {
              ajaxUrl: function($action, options) {
                return $action.attr('href').replace(/@@/g, "++nodiazo++/@@");
              },
              displayInModal: false
            },
            'input[name="form.button.AddAssignment"]': {},
            'a[href$="@@rules-controlpanel"]': {
              displayInModal: false
            }
          };
        });

      /***  Sharing  ***/
      $('#plone-action-local_roles > a').addClass('modal-trigger').patternModal({
        width: '80%',
        buttons: '#sharing-save-button, input[name="form.button.Cancel"]',
        automaticallyAddButtonActions: false,
        actions: {
          '#sharing-search-button': {},
          'a': {},
          'input[name="form.button.Cancel"]': {
            modalFunction: 'hide'
          },
          '#sharing-save-button': {
            onSuccess: function(modal, responseBody, state, xhr, form) {
              modal.redraw(responseBody);
              modal.$el.on('hidden.modal.patterns', function(e) {
                // We want to send the user to the original object *after* the status messages
                // have been displayed, and the user has closed the modal
                window.parent.location = modal.options.ajaxUrl.split('/').slice(0, -1).join('/');
              });
            }
          }
        }
      });

    }
  };

  registry.register(Toolbar);

  // initialize only if we are not in top frame (we are in toolbar's iframe)
  if (window.parent !== window) {
    registry.scan($('body'));
    Router.redirect();
    Router.start();
  }

  return Toolbar;

});
<commit_msg>position better<commit_after>// Author: Rok Garbas
// Contact: rok@garbas.si
// Version: 1.0
//
// Description:
//    plone.toolbar.js script makes sure that all dropdowns in Plone's toolbar
//    are in sync with iframe's stretching/schrinking.
//
// License:
//
// Copyright (C) 2010 Plone Foundation
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

if (window.jQuery) {
  define( "jquery", [], function () {
    "use strict";
    return window.jQuery;
  } );
}

define([
  'jquery',
  'mockup-router',
  'mockup-iframe',
  'mockup-registry',
  'mockup-patterns-toggle',
  'mockup-patterns-modal',
  'mockup-patterns-tinymce',
  'mockup-patterns-structure',
  'mockup-bundles-widgets'
], function($, Router, iframe, registry, Toggle, Modal, TinyMCE, Structure) {
  "use strict";

  // BBB: we need to hook pattern to classes which plone was using until now
  var Toolbar = {
    name: "plone-toolbar",
    transform: function($root) {
      if ($root.hasClass('modal')) {
        /* do not run in modal */
        return;
      }

      // Dropdown {{{

      // toggle class on click (shows dropdown)
      $('.toolbar-dropdown > a').each(function() {
        $(this).patternToggle({
          target: '.toolbar-dropdown',
          value: 'toolbar-dropdown-open',
          menu: 'parent'
        });
      });

      // make sure clicking on anything in the menu closes the toggled element
      $('.toolbar-dropdown .toolbar-dropdown-menu a').click(function(e) {
          $(this).parents('.toolbar-dropdown').children('a').trigger('click');
      });

      // at opening toolbar dropdown:
      // - close all other opened dropdown buttons
      // - stretch iframe
      // at closing dropdown shrink iframe
      $(document)
        .on('add-attr.toggle.patterns', '.toolbar-dropdown > a', function(e) {
          var $el = $(this);
          $('.toolbar-dropdown-open > a').each(function() {
            if ($el[0] !== $(this)[0]) {
              $(this).trigger('click');
            }
          });
          iframe.stretch();
        })
        .on('removed-attr.toggle.patterns', '.toolbar-dropdown > a', function(e) {
          iframe.shrink();
        });

      // }}}

      // Modals Helpers {{{

      // make sure we close all dropdowns when iframe is shrinking
      iframe.$el.on('shrink.iframe', function(e) {
        $('.toolbar-dropdown-open > a').each(function() {
          $(this).trigger('click');
        });
      });

      // integration of toolbar and modals
      $(document)
        .on('before-ajax.modal.patterns', 'a.modal-trigger, a.pat-modal', function(e) {
          var $el = $(this);
          $('.toolbar-dropdown-open > a').each(function() {
            if ($el[0] !== $(this)[0]) {
              $(this).trigger('click');
            }
          });
          $('body', iframe.document).css('overflow', 'hidden');
          iframe.stretch();
        })
        .on('show.modal.patterns', 'a.modal-trigger, a.pat-modal', function(e, modal) {
          var $el = $(this);
          $('.toolbar-dropdown-open > a').each(function() {
            if ($el[0] !== $(this)[0]) {
              $(this).trigger('click');
            }
          });
          $('body', iframe.document).css('overflow', 'hidden');
          iframe.stretch();
        })
        .on('hidden.modal.patterns', 'a.modal-trigger, a.pat-modal', function(e) {
          $('body', iframe.document).css('overflow', 'visible');
          iframe.shrink();
        });

      // }}}

      // Modals {{{

      // Contents
      $('#plone-action-folderContents > a').addClass('modal-trigger').patternModal({
        width: '96%',
        position: 'middle top',
        actionOptions: {
          onSuccess: function(modal, response, state, xhr, form){
          }
        }
      });

      // site setup
      $('#plone-sitesetup a').addClass('modal-trigger').patternModal({
        width: '80%',
        loadLinksWithinModal: false,
        actionOptions: {
          displayInModal: false
        }
      }).on('show.modal.patterns', function(evt, modal) {
        $('a[href]', modal.$modal).each(function(){
          var href = this.href;
          var parts = href.split('/');
          parts.splice(parts.length-1, 0, '++nodiazo++');
          href = parts.join('/');

          $(this).attr('href', href);
          $(this).click(function(){
            window.open(href);
          });
        });
      });

      // Manage portlets
      var portletOptions = {
        width: '50%',
        buttons: '.formControls > input[type="submit"],.actionButtons input[type="submit"]',
        automaticallyAddButtonActions: false
      };
      $('#toolbar-manage-portlets a,#manage-dashboard a')
      .addClass('pat-modal')
      .attr('data-pat-modal', JSON.stringify(portletOptions))
      .on('render.modal.patterns', function(e, modal) {
        // Kill the onchange method so we can wire up our own
        $('.section select', modal.$raw).removeAttr('onchange');
        modal.options.actions = {
            // Handle adding portlets via the select
            '.section select': {
              eventType: 'change',
              onSuccess: function(modal, response, state, xhr, form) {
                  if (modal.$modal.find('.pat-modal-buttons input').length === 0) {
                      // The portlet didn't have an edit form (e.g. calendar)
                      modal.reloadWindow();
                  }
              },
              ajaxUrl: function($action, options) {
                var portlet = $action.val();
                var form_action = $action.parents('form').attr('action');
                return form_action + portlet;
              }
            },
            '.actionButtons input': {
              // Handle errors on portlet submission
              error: '.fieldErrorBox',
              onSuccess: function(modal, response, state, xhr, form) {
                modal.reloadWindow();
              }
            },
            // Handle moving and hiding portlets
            '.portlet-action': {
              isForm: true
            }
          };
      })
      .on('hidden.modal.patterns', function(e, modal) {
          modal.reloadWindow();
        }
      );

      // Edit/Add
      $('#plone-contentmenu-factories ul li').addClass('is-content');
      $('#plone-contentmenu-factories ul li#plone-contentmenu-more').removeClass('is-content');
      $('#plone-contentmenu-factories ul li#plone-contentmenu-settings').removeClass('is-content');
      var editOptions = {
        width: '80%',
        backdropOptions: {
          closeOnClick: false
        },
        content: '#content',
        automaticallyAddButtonActions: false,
        actionOptions: {
          displayInModal: false
        },
        actions: {
          'input#form-buttons-save, .formControls input[name="form.button.save"]': {},
          'input#form-buttons-cancel, .formControls input[name="form.button.cancel"]': {
            modalFunction: 'hide'
          }
        },
        routerOptions: {
          id: 'edit',
          pathExp: '/edit$'
        }
      };
      var addOptions = editOptions;

      addOptions.actionOptions.redirectOnResponse = true;
      $('#plone-action-edit > a, #plone-contentmenu-factories ul li.is-content a')
        .addClass('pat-modal')
        .attr('data-pat-modal', JSON.stringify(editOptions));

      delete addOptions.routerOptions;
      $('#plone-contentmenu-factories ul li.is-content a')
        .addClass('pat-modal')
        .attr('data-pat-modal', JSON.stringify(addOptions));

      // Content Rules
      var rulesOptions = {
        width: '80%',
        content: '#content-core',
        loadLinksWithinModal: false
      };
      $('#plone-action-contentrules > a')
        .addClass('pat-modal')
        .attr('data-pat-modal', JSON.stringify(rulesOptions)).
        on('render.modal.patterns', function(e, modal) {
          modal.options.actions = {
            'table.listing a': {
              ajaxUrl: function($action, options) {
                return $action.attr('href').replace(/@@/g, "++nodiazo++/@@");
              },
              displayInModal: false
            },
            'input[name="form.button.AddAssignment"]': {},
            'a[href$="@@rules-controlpanel"]': {
              displayInModal: false
            }
          };
        });

      /***  Sharing  ***/
      $('#plone-action-local_roles > a').addClass('modal-trigger').patternModal({
        width: '80%',
        buttons: '#sharing-save-button, input[name="form.button.Cancel"]',
        automaticallyAddButtonActions: false,
        actions: {
          '#sharing-search-button': {},
          'a': {},
          'input[name="form.button.Cancel"]': {
            modalFunction: 'hide'
          },
          '#sharing-save-button': {
            onSuccess: function(modal, responseBody, state, xhr, form) {
              modal.redraw(responseBody);
              modal.$el.on('hidden.modal.patterns', function(e) {
                // We want to send the user to the original object *after* the status messages
                // have been displayed, and the user has closed the modal
                window.parent.location = modal.options.ajaxUrl.split('/').slice(0, -1).join('/');
              });
            }
          }
        }
      });

    }
  };

  registry.register(Toolbar);

  // initialize only if we are not in top frame (we are in toolbar's iframe)
  if (window.parent !== window) {
    registry.scan($('body'));
    Router.redirect();
    Router.start();
  }

  return Toolbar;

});
<|endoftext|>


<commit_before>// Author: Rok Garbas
// Contact: rok@garbas.si
// Version: 1.0
// Description:
//
// License:
//
// Copyright (C) 2010 Plone Foundation
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

/*jshint bitwise:true, curly:true, eqeqeq:true, immed:true, latedef:true,
  newcap:true, noarg:true, noempty:true, nonew:true, plusplus:true,
  undef:true, strict:true, trailing:true, browser:true, evil:true */
/*global define:false */

if (window.jQuery) {
  define( "jquery", [], function () {
    "use strict";
    return window.jQuery;
  } );
}

define([
  'jquery',
  'jam/Patterns/src/registry',
  'js/patterns/select2',
  'js/patterns/pickadate',
  'js/patterns/autotoc',
  'js/patterns/accessibility',
  'js/patterns/relateditems'
], function($, registry) {
  "use strict";

  // BBB: we need to hook pattern to classes which plone was using until now
  var Widgets = {
    name: "plone-widgets",
    transform: function($root) {

      // apply autotoc pattern where enableFormTabbing exists
      var $match = $root.filter('.enableFormTabbing');
      $match = $match.add($root.find('.enableFormTabbing'));
      $match.addClass('pat-autotoc');
      $match.attr({
        'data-pat-autotoc-levels': 'legend',
        'data-pat-autotoc-section': 'fieldset',
        'data-pat-autotoc-klass': 'autotabs'
      });

      // activate accessibility pattern by default
      $root.addClass('pat-accessibility');
      $root.attr({
        'data-pat-accessibility-smallbtn': "#accessibility-smallText",
        'data-pat-accessibility-normalbtn': "#accessibility-normalText",
        'data-pat-accessibility-largebtn': "#accessibility-largeText"
      });
    },
    scan: function(selector) {
      registry.scan($(selector));
    }
  };

  registry.register(Widgets);

  return Widgets;
});
<commit_msg>Integrated formUnloadAlert<commit_after>// Author: Rok Garbas
// Contact: rok@garbas.si
// Version: 1.0
// Description:
//
// License:
//
// Copyright (C) 2010 Plone Foundation
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

/*jshint bitwise:true, curly:true, eqeqeq:true, immed:true, latedef:true,
  newcap:true, noarg:true, noempty:true, nonew:true, plusplus:true,
  undef:true, strict:true, trailing:true, browser:true, evil:true */
/*global define:false */

if (window.jQuery) {
  define( "jquery", [], function () {
    "use strict";
    return window.jQuery;
  } );
}

define([
  'jquery',
  'jam/Patterns/src/registry',
  'js/patterns/select2',
  'js/patterns/pickadate',
  'js/patterns/autotoc',
  'js/patterns/accessibility',
  'js/patterns/relateditems',
  'js/patterns/formUnloadAlert'
], function($, registry) {
  "use strict";

  // BBB: we need to hook pattern to classes which plone was using until now
  var Widgets = {
    name: "plone-widgets",
    transform: function($root) {

      // apply autotoc pattern where enableFormTabbing exists
      var $match = $root.filter('.enableFormTabbing');
      $match = $match.add($root.find('.enableFormTabbing'));
      $match.addClass('pat-autotoc');
      $match.attr({
        'data-pat-autotoc-levels': 'legend',
        'data-pat-autotoc-section': 'fieldset',
        'data-pat-autotoc-klass': 'autotabs'
      });

      // activate accessibility pattern by default
      $root.addClass('pat-accessibility');
      $root.attr({
        'data-pat-accessibility-smallbtn': "#accessibility-smallText",
        'data-pat-accessibility-normalbtn': "#accessibility-normalText",
        'data-pat-accessibility-largebtn': "#accessibility-largeText"
      });

      // apply formUnloadAlert pattern where enableUnloadProtection exists
      var $match = $root.filter('.enableUnloadProtection');
      $match = $match.add($root.find('.enableUnloadProtection'));
      $match.addClass('pat-formunloadalert');
      $match.attr({
        'data-pat-formunloadalert-message': window.form_modified_message
      });

    },
    scan: function(selector) {
      registry.scan($(selector));
    }
  };

  registry.register(Widgets);

  return Widgets;
});
<|endoftext|>


<commit_before>define('template/helpers/dateFormat', ["handlebars"], function(Handlebars) {
    function dateFormat(string) {
        if(!string) {
            return "";
        }
        try {
            date = new Date(string);
            return date.getDay() +  "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
        } catch (err) {
            console.log(err);
            return "";
        }
    }
    Handlebars.registerHelper('dateFormat', dateFormat);
    return dateFormat;
});
<commit_msg>Corrected date helper to use day of the month instead of day of the week (!).<commit_after>define('template/helpers/dateFormat', ["handlebars"], function(Handlebars) {
    function dateFormat(string) {
        if(!string) {
            return "";
        }
        try {
            date = new Date(string);
            return date.getDate() +  "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
        } catch (err) {
            console.log(err);
            return "";
        }
    }
    Handlebars.registerHelper('dateFormat', dateFormat);
    return dateFormat;
});
<|endoftext|>


<commit_before>var colors = ["blue", "red", "white", "gold"];
var names = ["Lucas", "Ivan", "Frida", "Bella"];

colors.push("pink")
names.push("Hiedi")

var horseObject = {},
    i,
    keys =  names //['one', 'two', 'three'],
    values = colors  //['a', 'b', 'c'];

for (i = 0; i < keys.length; i++) {
    horseObject[keys[i]] = values[i];
    horseObject
}

//for (var i = 0; i < colors.length; i++) {
//	console.log(colors[i]);
//}

//console.log("Like my coat, my horses have many colors " + names['name'] + "-" + colors['colors']);

//============CAR=======================

var car = {model: 'Spot', year: 3, topSpeed: "100mph"};

function Car(model, year, topSpeed) {
	console.log("Our new car:", this);

	this.model = model;
	this.year = year;
	this.topSpeed = topSpeed;
	this.go = function() { console.log("Vrrrm!"); };

	console.log("CAR INITIALIZATION COMPLETE");
}
console.log("Let's build a new car ...");
// Here is where we call that constructor function
// that we just made ...
var anotherCar = new Car("Mustang", 2016, "145mph");
console.log(anotherCar);
console.log("Our new car can go:");
anotherCar.go();
console.log("----");

console.log("Let's build another car ...");
var yetAnotherCar = new Car("280z", 1978, "155mph");
console.log(yetAnotherCar);
console.log("This new dog can go, too:");
yetAnotherCar.go();
console.log("----");

//NEED TO ADD driver code<commit_msg>correcting commit errors, no substantial change from previous commit<commit_after>var colors = ["blue", "red", "white", "gold"];
var names = ["Lucas", "Ivan", "Frida", "Bella"];

colors.push("pink")
names.push("Hiedi")

var horseObject = {},
    i,
    keys =  names //['one', 'two', 'three'],
    values = colors  //['a', 'b', 'c'];

for (i = 0; i < keys.length; i++) {
    horseObject[keys[i]] = values[i];
    horseObject
}

//for (var i = 0; i < colors.length; i++) {
//	console.log(colors[i]);
//}

//console.log("Like my coat, my horses have many colors " + names['name'] + "-" + colors['colors']);

//============CAR================

var car = {model: 'Spot', year: 3, topSpeed: "100mph"};

function Car(model, year, topSpeed) {
	console.log("Our new car:", this);

	this.model = model;
	this.year = year;
	this.topSpeed = topSpeed;
	this.go = function() { console.log("Vrrrm!"); };

	console.log("CAR INITIALIZATION COMPLETE");
}
console.log("Let's build a new car ...");
// Here is where we call that constructor function
// that we just made ...
var anotherCar = new Car("Mustang", 2016, "145mph");
console.log(anotherCar);
console.log("Our new car can go:");
anotherCar.go();
console.log("----");

console.log("Let's build another car ...");
var yetAnotherCar = new Car("280z", 1978, "155mph");
console.log(yetAnotherCar);
console.log("This new dog can go, too:");
yetAnotherCar.go();
console.log("----");

//NEED TO ADD driver code<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.u2',
  name: 'Element',

  constants: {
    INITIAL: {
      output: function(out) {
        out('<', this.nodeName);
        if ( this.id ) out(' id="', this.id, '"');

        for ( key in this.attributeMap ) {
          var value = this.attributeMap[key];

          out(' ', key);
          if ( value !== undefined )
            out('="', value, '"');
        }
        if ( ! this.ILLEGAL_CLOSE_TAGS[this.nodeName] &&
             ( ! this.OPTIONAL_CLOSE_TAGS[this.nodeName] || this.childNodes.length ) ) {
          out('>');
          this.outputInnerHTML(out);
          out('</', this.nodeName);
        }
        out('>');

        this.state = this.OUTPUT;

        return out;
      },
      load:          function() { console.error('Must output before loading.'); },
      unload:        function() { console.error('Must output and load before unloading.'); },
      destroy:       function() { },
      onSetCls:      function() { },
      onAddListener: function() { },
      onSetStyle:    function() { },
      onSetAttr:     function() { },
      onAddChildren: function() { },
      toString:      function() { return 'INITIAL'; }
    },
    OUTPUT: {
      output:        function(out) {
        // Only warn because it could be useful for debugging.
        console.error('Duplicate output.');
        return this.INITIAL.output.call(this, out);
      },
      load:          function() {
        this.state = this.LOADED;
      },
      unload:        function() { console.error('Must load before unloading.'); },
      destroy:       function() { },
      onSetCls:      function(cls, enabled) {
        this.id$el.classList[enabled ? 'add' : 'remove'](cls);
      },
      onAddListener: function(topic, listener) {
        this.id$el.addEventListener(topic, listener);
      },
      onSetStyle:    function(key, value) {
        this.id$el.style[key] = value;
      },
      onSetAttr:     function(key, value) {
        this.id$el[key] = value;
      },
      onAddChildren: function() {
        var out = this.createOutputStream();
        for ( var i = 0 ; i < arguments.length ; i++ ) {
          out(arguments[i]);
        }
        this.id$el.insertAdjacentHTML('beforeend', out);
      },
      toString:      function() { return 'OUTPUT'; }
    },
    LOADED: {
      output:        function(out) { console.warn('Duplicate output.'); },
      load:          function() { console.error('Duplicate load.'); },
      unload:        function() {
        this.state = this.UNLOADED;
      },
      destroy:       function() { },
      onSetCls:      function(cls, enabled) {
        this.id$el.classList[enabled ? 'add' : 'remove'](cls);
      },
      onAddListener: function(topic, listener) {
        this.id$el.addEventListener(topic, listener);
      },
      onSetStyle:    function() { },
      onSetAttr:     function(key, value) {
        this.id$el[key] = value;
      },
      onAddChildren: function() {
        var out = this.createOutputStream();
        for ( var i = 0 ; i < arguments.length ; i++ ) {
          out(arguments[i]);
        }
        this.id$el.insertAdjacentHTML('beforeend', out);
      },
      toString:      function() { return 'LOADED'; }
    },
    UNLOADED: {
      output:        function() { },
      load:          function() {
        this.state = this.LOADED;
      },
      unload:        function() { },
      destroy:       function() { },
      onSetCls:      function() { },
      onAddListener: function() { },
      onSetStyle:    function() { },
      onSetAttr:     function() { },
      onAddChildren: function() { },
      toString:      function() { return 'UNLOADED'; }
    },
    DESTROYED: { // Needed?
      output:        function() { throw 'Attempt to output() destroyed Element.'; },
      load:          function() { throw 'Attempt to load() destroyed Element.'; },
      unload:        function() { throw 'Attempt to unload() destroyed Element.';},
      destroy:       function() { },
      onSetCls:      function() { },
      onAddListener: function() { },
      onSetStyle:    function() { },
      onSetAttr:     function() { },
      onAddChildren: function() { },
      toString:      function() { return 'DESTROYED'; }
    },

    OPTIONAL_CLOSE_TAGS: {
      HTML: true,
      HEAD: true,
      BODY: true,
      P: true,
      DT: true,
      DD: true,
      LI: true,
      OPTION: true,
      THEAD: true,
      TH: true,
      TBODY: true,
      TR: true,
      TD: true,
      TFOOT: true,
      COLGROUP: true
    },
    ILLEGAL_CLOSE_TAGS: {
      IMG: true,
      INPUT: true,
      BR: true,
      HR: true,
      FRAME: true,
      AREA: true,
      BASE: true,
      BASEFONT: true,
      COL: true,
      ISINDEX: true,
      LINK: true,
      META: true,
      PARAM: true
    }
  },

  properties: [
    {
      name: 'state',
      factory: function () { return this.INITIAL; }
    },
    {
      model_: 'foam.u2.EIDProperty',
      name: 'id'
    },
    {
      name: 'nodeName'/*,
      preSet: function(_, v) {
        return v.toLowerCase();
      }*/
    },
    {
      name: 'attributeMap',
      transient: true,
      factory: function() { return {}; }
    },
    {
      name: 'attributes',
      factory: function() { return []; },
      postSet: function(_, attrs) {
        for ( var i = 0 ; i < attrs.length ; i++ )
          this.attributeMap[attrs[i].name] = attrs[i];
      }
    },
    {
      name: 'classes',
      factory: function() { return []; }
    },
    {
      name: 'css',
      factory: function() { return []; }
    },
    {
      name: 'childNodes',
      factory: function() { return []; }
    },
    {
      name: 'elListeners',
      factory: function() { return []; }
    },
    {
      name: 'children',
      transient: true,
      getter: function() {
        return this.childNodes.filter(function(c) { return typeof c !== 'string'; });
      }
    },
    {
      name: 'outerHTML',
      transient: true,
      getter: function() { return this.output(this.createOutputStream()); }
    },
    {
      name: 'innerHTML',
      transient: true,
      getter: function() { return this.outputInnerHTML(this.createOutputStream()); }
    }
  ],

  methods: [

    //
    // State
    //
    function onSetAttr(key, value) {
      this.state.onSetAttr.call(this, key, value);
    },

    function onAddChildren(/* vargs */) {
      this.state.onAddChildren.apply(this, arguments);
    },

    function onAddListener(topic, listener) {
      this.state.onAddListener.call(this, topic, listener);
    },

    function onSetStyle(key, value) {
      this.state.onSetStyle.call(this, key, value);
    },

    function onSetCls(cls, add) {
      this.state.onSetCls.call(this, cls, add);
    },

    //
    // Lifecycle
    //
    function load() { this.state.load.call(this); },

    function unload() { this.state.unload.call(this); },

    function destroy() { this.state.destroy.call(this); },

    //
    // DOM Compatibility
    //
    function setAttribute(name, value) {
      var attr = this.getAttributeNode(name);

      if ( attr ) {
        attr.value = value;
      } else {
        attr = {name: name, value: value};
        this.attributes.push(attr);
        this.attributeMap[name] = attr;
      }
    },

    function getAttributeNode(name) { return this.attributeMap[name]; },

    function getAttribute(name) {
      var attr = this.getAttributeNode(name);
      return attr && attr.value;
    },

    function appendChild(c) { this.childNodes.push(c); },

    function removeChild(c) {
      for ( var i = 0; i < this.childNodes.length; ++i ) {
        if ( this.childNodes[i] === c ) {
          this.childNodes.splice(i, 1);
          break;
        }
      }
    },

    //
    // Fluent Methods
    //
    function on(topic, listener) {
      this.elListeners.push([topic, listener]);
      this.onAddListener(topic, listener);
      return this;
    },

    function cls(cls, opt_enabled) {
      var enabled = opt_enabled === undefined ? true : opt_enabled ;
      this.classes[cls] = enabled;
      this.onSetCls(cls, enabled);
      return this;
    },

    function attr(key, value) {
      this.attributeMap[key] = value;
      this.onSetAttr(key, value);
      return this;
    },

    function attrs(map) {
      for ( key in map ) this.attr(key, map[key]);
      return this;
    },

    function style(key, value) {
      this.css.push([key, value]);
      this.onSetStyle(key, value);
      return this;
    },

    function styles(map) {
      for ( key in map ) this.style(key, map[key]);
      return this;
    },

    function c() {
      this.childNodes.push.apply(this.childNodes, arguments);
      this.onAddChildren.apply(this, arguments);
      return this;
    },

    //
    // Output Methods
    //
    function output(out) { return this.state.output.call(this, out); },

    function outputInnerHTML(out) {
      for ( var i = 0 ; i < this.childNodes.length ; i++ )
        out(this.childNodes[i]/*.toString()*/);
      return out;
    },

    function createOutputStream() {
      var self = this;
      var buf = [];
      var f = function templateOut(/* arguments */) {
        for ( var i = 0 ; i < arguments.length ; i++ ) {
          var o = arguments[i];
          if ( typeof o === 'string' ) {
            buf.push(o);
          } else {
            if ( o && o.toView_ ) o = o.toView_();
            if ( ! ( o === null || o === undefined ) ) {
              if ( o.output ) {
                o.output(f);
              } else if ( o.toHTML ) {
                buf.push(o.toHTML());
              } else {
                buf.push(o);
              }
              if ( o.initHTML && self && obj.addChild ) self.addChild(o);
            }
          }
        }
      };

      f.toString = function() {
        if ( buf.length === 0 ) return '';
        if ( buf.length > 1 ) buf = [buf.join('')];
        return buf[0];
      }

      return f;
    },

    function write(document) {
      /* For debugging, not production. */
      document.writeln(this.outerHTML);
    },

    function toString() { return this.outerHTML; }
  ]
});

function E(opt_nodeName) {
  var e = foam.u2.Element.create();
  if ( opt_nodeName ) e.nodeName = opt_nodeName;
  return e;
}

/*
  TODO: focus?, compile, deepClone, pass data, don't clone if literal
*/
<commit_msg>Element produces warnings when LOADED but missing.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.u2',
  name: 'Element',

  constants: {
    INITIAL: {
      output: function(out) {
        out('<', this.nodeName);
        if ( this.id ) out(' id="', this.id, '"');

        for ( key in this.attributeMap ) {
          var value = this.attributeMap[key];

          out(' ', key);
          if ( value !== undefined )
            out('="', value, '"');
        }
        if ( ! this.ILLEGAL_CLOSE_TAGS[this.nodeName] &&
             ( ! this.OPTIONAL_CLOSE_TAGS[this.nodeName] || this.childNodes.length ) ) {
          out('>');
          this.outputInnerHTML(out);
          out('</', this.nodeName);
        }
        out('>');

        this.state = this.OUTPUT;

        return out;
      },
      load:          function() { console.error('Must output before loading.'); },
      unload:        function() { console.error('Must output and load before unloading.'); },
      destroy:       function() { },
      onSetCls:      function() { },
      onAddListener: function() { },
      onSetStyle:    function() { },
      onSetAttr:     function() { },
      onAddChildren: function() { },
      toString:      function() { return 'INITIAL'; }
    },
    OUTPUT: {
      output:        function(out) {
        // Only warn because it could be useful for debugging.
        console.error('Duplicate output.');
        return this.INITIAL.output.call(this, out);
      },
      load:          function() {
        this.state = this.LOADED;
      },
      unload:        function() { console.error('Must load before unloading.'); },
      destroy:       function() { },
      onSetCls:      function(cls, enabled) {
        this.id$el.classList[enabled ? 'add' : 'remove'](cls);
      },
      onAddListener: function(topic, listener) {
        this.id$el.addEventListener(topic, listener);
      },
      onSetStyle:    function(key, value) {
        this.id$el.style[key] = value;
      },
      onSetAttr:     function(key, value) {
        this.id$el[key] = value;
      },
      onAddChildren: function() {
        var out = this.createOutputStream();
        for ( var i = 0 ; i < arguments.length ; i++ ) {
          out(arguments[i]);
        }
        this.id$el.insertAdjacentHTML('beforeend', out);
      },
      toString:      function() { return 'OUTPUT'; }
    },
    LOADED: {
      output:        function(out) { console.warn('Duplicate output.'); },
      load:          function() { console.error('Duplicate load.'); },
      unload:        function() {
        this.state = this.UNLOADED;
      },
      destroy:       function() { },
      onSetCls:      function(cls, enabled) {
        var e = this.id$el;
        if ( ! e ) {
          console.warn('Missing Element: ', this.id);
          return
        }
        e.classList[enabled ? 'add' : 'remove'](cls);
      },
      onAddListener: function(topic, listener) {
        this.id$el.addEventListener(topic, listener);
      },
      onSetStyle:    function() { },
      onSetAttr:     function(key, value) {
        this.id$el[key] = value;
      },
      onAddChildren: function() {
        var e = this.id$el;
        if ( ! e ) {
          console.warn('Missing Element: ', this.id);
          return
        }
        var out = this.createOutputStream();
        for ( var i = 0 ; i < arguments.length ; i++ ) {
          out(arguments[i]);
        }
        e.insertAdjacentHTML('beforeend', out);
      },
      toString:      function() { return 'LOADED'; }
    },
    UNLOADED: {
      output:        function() { },
      load:          function() {
        this.state = this.LOADED;
      },
      unload:        function() { },
      destroy:       function() { },
      onSetCls:      function() { },
      onAddListener: function() { },
      onSetStyle:    function() { },
      onSetAttr:     function() { },
      onAddChildren: function() { },
      toString:      function() { return 'UNLOADED'; }
    },
    DESTROYED: { // Needed?
      output:        function() { throw 'Attempt to output() destroyed Element.'; },
      load:          function() { throw 'Attempt to load() destroyed Element.'; },
      unload:        function() { throw 'Attempt to unload() destroyed Element.';},
      destroy:       function() { },
      onSetCls:      function() { },
      onAddListener: function() { },
      onSetStyle:    function() { },
      onSetAttr:     function() { },
      onAddChildren: function() { },
      toString:      function() { return 'DESTROYED'; }
    },

    OPTIONAL_CLOSE_TAGS: {
      HTML: true,
      HEAD: true,
      BODY: true,
      P: true,
      DT: true,
      DD: true,
      LI: true,
      OPTION: true,
      THEAD: true,
      TH: true,
      TBODY: true,
      TR: true,
      TD: true,
      TFOOT: true,
      COLGROUP: true
    },
    ILLEGAL_CLOSE_TAGS: {
      IMG: true,
      INPUT: true,
      BR: true,
      HR: true,
      FRAME: true,
      AREA: true,
      BASE: true,
      BASEFONT: true,
      COL: true,
      ISINDEX: true,
      LINK: true,
      META: true,
      PARAM: true
    }
  },

  properties: [
    {
      name: 'state',
      factory: function () { return this.INITIAL; }
    },
    {
      model_: 'foam.u2.EIDProperty',
      name: 'id'
    },
    {
      name: 'nodeName'/*,
      preSet: function(_, v) {
        return v.toLowerCase();
      }*/
    },
    {
      name: 'attributeMap',
      transient: true,
      factory: function() { return {}; }
    },
    {
      name: 'attributes',
      factory: function() { return []; },
      postSet: function(_, attrs) {
        for ( var i = 0 ; i < attrs.length ; i++ )
          this.attributeMap[attrs[i].name] = attrs[i];
      }
    },
    {
      name: 'classes',
      factory: function() { return []; }
    },
    {
      name: 'css',
      factory: function() { return []; }
    },
    {
      name: 'childNodes',
      factory: function() { return []; }
    },
    {
      name: 'elListeners',
      factory: function() { return []; }
    },
    {
      name: 'children',
      transient: true,
      getter: function() {
        return this.childNodes.filter(function(c) { return typeof c !== 'string'; });
      }
    },
    {
      name: 'outerHTML',
      transient: true,
      getter: function() { return this.output(this.createOutputStream()); }
    },
    {
      name: 'innerHTML',
      transient: true,
      getter: function() { return this.outputInnerHTML(this.createOutputStream()); }
    }
  ],

  methods: [

    //
    // State
    //
    function onSetAttr(key, value) {
      this.state.onSetAttr.call(this, key, value);
    },

    function onAddChildren(/* vargs */) {
      this.state.onAddChildren.apply(this, arguments);
    },

    function onAddListener(topic, listener) {
      this.state.onAddListener.call(this, topic, listener);
    },

    function onSetStyle(key, value) {
      this.state.onSetStyle.call(this, key, value);
    },

    function onSetCls(cls, add) {
      this.state.onSetCls.call(this, cls, add);
    },

    //
    // Lifecycle
    //
    function load() { this.state.load.call(this); },

    function unload() { this.state.unload.call(this); },

    function destroy() { this.state.destroy.call(this); },

    //
    // DOM Compatibility
    //
    function setAttribute(name, value) {
      var attr = this.getAttributeNode(name);

      if ( attr ) {
        attr.value = value;
      } else {
        attr = {name: name, value: value};
        this.attributes.push(attr);
        this.attributeMap[name] = attr;
      }
    },

    function getAttributeNode(name) { return this.attributeMap[name]; },

    function getAttribute(name) {
      var attr = this.getAttributeNode(name);
      return attr && attr.value;
    },

    function appendChild(c) { this.childNodes.push(c); },

    function removeChild(c) {
      for ( var i = 0; i < this.childNodes.length; ++i ) {
        if ( this.childNodes[i] === c ) {
          this.childNodes.splice(i, 1);
          break;
        }
      }
    },

    //
    // Fluent Methods
    //
    function on(topic, listener) {
      this.elListeners.push([topic, listener]);
      this.onAddListener(topic, listener);
      return this;
    },

    function cls(cls, opt_enabled) {
      var enabled = opt_enabled === undefined ? true : opt_enabled ;
      this.classes[cls] = enabled;
      this.onSetCls(cls, enabled);
      return this;
    },

    function attr(key, value) {
      this.attributeMap[key] = value;
      this.onSetAttr(key, value);
      return this;
    },

    function attrs(map) {
      for ( key in map ) this.attr(key, map[key]);
      return this;
    },

    function style(key, value) {
      this.css.push([key, value]);
      this.onSetStyle(key, value);
      return this;
    },

    function styles(map) {
      for ( key in map ) this.style(key, map[key]);
      return this;
    },

    function c() {
      this.childNodes.push.apply(this.childNodes, arguments);
      this.onAddChildren.apply(this, arguments);
      return this;
    },

    //
    // Output Methods
    //
    function output(out) { return this.state.output.call(this, out); },

    function outputInnerHTML(out) {
      for ( var i = 0 ; i < this.childNodes.length ; i++ )
        out(this.childNodes[i]/*.toString()*/);
      return out;
    },

    function createOutputStream() {
      var self = this;
      var buf = [];
      var f = function templateOut(/* arguments */) {
        for ( var i = 0 ; i < arguments.length ; i++ ) {
          var o = arguments[i];
          if ( typeof o === 'string' ) {
            buf.push(o);
          } else {
            if ( o && o.toView_ ) o = o.toView_();
            if ( ! ( o === null || o === undefined ) ) {
              if ( o.output ) {
                o.output(f);
              } else if ( o.toHTML ) {
                buf.push(o.toHTML());
              } else {
                buf.push(o);
              }
              if ( o.initHTML && self && obj.addChild ) self.addChild(o);
            }
          }
        }
      };

      f.toString = function() {
        if ( buf.length === 0 ) return '';
        if ( buf.length > 1 ) buf = [buf.join('')];
        return buf[0];
      }

      return f;
    },

    function write(document) {
      /* For debugging, not production. */
      document.writeln(this.outerHTML);
    },

    function toString() { return this.outerHTML; }
  ]
});

function E(opt_nodeName) {
  var e = foam.u2.Element.create();
  if ( opt_nodeName ) e.nodeName = opt_nodeName;
  return e;
}

/*
  TODO: focus?, compile, deepClone, pass data, don't clone if literal
*/
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.ui',
  name: 'WebView',
  extendsModel: 'foam.ui.SimpleView',
  imports: [
    'window',
  ],
  help: 'A view that renders the HTML given to it.',
  properties: [
    {
      name: 'data',
    },
    {
      name: 'intervalId',
    },
  ],
  methods: {
    toHTML: function() {
      var id = this.id;
      return '';
    },
    initHTML: function() {
      this.SUPER();

      this.$.contentDocument.write(this.data);
      // This is a lazy way of handling the change in size when things like
      // images load asynchronously.
      this.intervalId = this.window.setInterval(this.onResize, 500);
      this.onResize();
    },
    destroy: function() {
      this.window.clearInterval(this.intervalId);
    },
  },
  listeners: [
    {
      name: 'onResize',
      isMerged: 500,
      code: function() {
        this.$.style.height = this.$.contentDocument.documentElement.offsetHeight;
      }
    }
  ]
});
<commit_msg>Fix some bugs in foam.ui.WebView.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.ui',
  name: 'WebView',
  extendsModel: 'foam.ui.SimpleView',
  imports: [
    'window',
  ],
  help: 'A view that renders the HTML given to it.',
  properties: [
    {
      name: 'data',
    },
    {
      name: 'intervalId',
    },
  ],
  methods: {
    init: function() {
      this.SUPER();
      this.data$.addListener(function() {
        this.$.outerHTML = this.toHTML();
        this.initHTML();
      }.bind(this));
    },
    toHTML: function() {
      var id = this.id;
      return '';
    },
    initHTML: function() {
      this.SUPER();

      this.$.contentDocument.write(this.data);
      // This is a lazy way of handling the change in size when things like
      // images load asynchronously.
      this.intervalId = this.window.setInterval(this.onResize, 500);
      this.onResize();
    },
    destroy: function() {
      this.window.clearInterval(this.intervalId);
    },
  },
  listeners: [
    {
      name: 'onResize',
      isMerged: 500,
      code: function() {
        if ( ! this.$ ) {
          this.window.clearInterval(this.intervalId);
          return;
        }
        if ( this.$.contentDocument.documentElement )
          this.$.style.height = this.$.contentDocument.documentElement.offsetHeight;
      }
    }
  ]
});
<|endoftext|>


<commit_before>;(function($){
/**
 * jqGrid extension for manipulating columns properties
 * Piotr Roznicki roznicki@o2.pl
 * http://www.roznicki.prv.pl
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
**/
$.fn.extend({
	setColumns : function(p) {
		p = $.extend({
			top : 0,
			left: 0,
			width: 200,
			height: 195,
			modal: false,
			drag: true,
			closeicon: 'ico-close.gif',
			beforeShowForm: null,
			afterShowForm: null,
			afterSubmitForm: null,
			jqModal : false,
			closeOnEscape : true,
			ShrinkToFit : true
		}, $.jgrid.col, p ||{});
		return this.each(function(){
			var $t = this;
			if (!$t.grid ) { return; }
			var onBeforeShow = typeof p.beforeShowForm === 'function' ? true: false;
			var onAfterShow = typeof p.afterShowForm === 'function' ? true: false;
			var onAfterSubmit = typeof p.afterSubmitForm === 'function' ? true: false;
			if(!p.imgpath) { p.imgpath= $t.p.imgpath; } // Added From Tony Tomov
			var gID = $t.p.id;
			var IDs = {themodal:'colmod'+gID,modalhead:'colhd'+gID,modalcontent:'colcnt'+gID};
			var dtbl = "ColTbl_"+gID;
			if ( $("#"+IDs.themodal).html() != null ) {
				if(onBeforeShow) { p.beforeShowForm($("#"+dtbl)); }
				viewModal("#"+IDs.themodal,{gbox:"#gbox_"+gID,jqm:false});
				if(onAfterShow) { p.afterShowForm($("#"+dtbl)); }
			} else {
				var tbl =$("

");
				for(i=0;i<this.p.colNames.length;i++){
					if(!$t.p.colModel[i].hidedlg) { // added from T. Tomov
						$(tbl).append("
<input type='checkbox' id='col_" + this.p.colModel[i].name + "' class='cbox' value='T' " +
						((this.p.colModel[i].hidden===false)?"checked":"") + "/>" +  "" + this.p.colNames[i] + "(" + this.p.colModel[i].name + ")
");
					}
				}
				var bS  ="<input id='dData' type='button' value='"+p.bSubmit+"'/>";
				var bC  ="<input id='eData' type='button' value='"+p.bCancel+"'/>";
				$(tbl).append("
"+bS+" "+bC+"
");
				p.gbox = "#gbox_"+gID;
				createModal(IDs,tbl,p,$t.grid.hDiv,$t.grid.hDiv);
				//if( p.drag) { DnRModal("#"+IDs.themodal,"#"+IDs.modalhead+" td.modaltext"); }
				$("#dData","#"+dtbl).click(function(e){
					for(i=0;i<$t.p.colModel.length;i++){
						if(!$t.p.colModel[i].hidedlg) { // added from T. Tomov
							if($("#col_" + $t.p.colModel[i].name).attr("checked")) {
								$($t).showCol($t.p.colModel[i].name);
								$("#col_" + $t.p.colModel[i].name).attr("defaultChecked",true); // Added from T. Tomov IE BUG
							} else {
								$($t).hideCol($t.p.colModel[i].name);
								$("#col_" + $t.p.colModel[i].name).attr("defaultChecked",""); // Added from T. Tomov IE BUG
							}
						}
					}
					if(p.ShrinkToFit===true) {
						$($t).setGridWidth($t.grid.width-0.01,true);
					}
					hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:false});
					if (onAfterSubmit) { p.afterSubmitForm($("#"+dtbl)); }
					return false;
				});
				$("#eData", "#"+dtbl).click(function(e){
					hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:false});
					return false;
				});
				$("#dData, #eData","#"+dtbl).addClass('ui-state-default ui-corner-all')
				.css({padding:".2em .5em", cursor: 'pointer'})
				.hover(
				   function(){$(this).addClass('ui-state-hover');},
				   function(){$(this).removeClass('ui-state-hover');}
				);
				if(onBeforeShow) { p.beforeShowForm($("#"+dtbl)); }
				viewModal("#"+IDs.themodal,{gbox:"#gbox_"+gID,jqm:false});
				if(onAfterShow) { p.afterShowForm($("#"+dtbl)); }
			}
		});
	}
});
})(jQuery);<commit_msg>Also set the default value to false in setColumns module<commit_after>;(function($){
/**
 * jqGrid extension for manipulating columns properties
 * Piotr Roznicki roznicki@o2.pl
 * http://www.roznicki.prv.pl
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
**/
$.fn.extend({
	setColumns : function(p) {
		p = $.extend({
			top : 0,
			left: 0,
			width: 200,
			height: 195,
			modal: false,
			drag: true,
			closeicon: 'ico-close.gif',
			beforeShowForm: null,
			afterShowForm: null,
			afterSubmitForm: null,
			jqModal : false,
			closeOnEscape : true,
			ShrinkToFit : false
		}, $.jgrid.col, p ||{});
		return this.each(function(){
			var $t = this;
			if (!$t.grid ) { return; }
			var onBeforeShow = typeof p.beforeShowForm === 'function' ? true: false;
			var onAfterShow = typeof p.afterShowForm === 'function' ? true: false;
			var onAfterSubmit = typeof p.afterSubmitForm === 'function' ? true: false;
			if(!p.imgpath) { p.imgpath= $t.p.imgpath; } // Added From Tony Tomov
			var gID = $t.p.id;
			var IDs = {themodal:'colmod'+gID,modalhead:'colhd'+gID,modalcontent:'colcnt'+gID};
			var dtbl = "ColTbl_"+gID;
			if ( $("#"+IDs.themodal).html() != null ) {
				if(onBeforeShow) { p.beforeShowForm($("#"+dtbl)); }
				viewModal("#"+IDs.themodal,{gbox:"#gbox_"+gID,jqm:false});
				if(onAfterShow) { p.afterShowForm($("#"+dtbl)); }
			} else {
				var tbl =$("

");
				for(i=0;i<this.p.colNames.length;i++){
					if(!$t.p.colModel[i].hidedlg) { // added from T. Tomov
						$(tbl).append("
<input type='checkbox' id='col_" + this.p.colModel[i].name + "' class='cbox' value='T' " +
						((this.p.colModel[i].hidden===false)?"checked":"") + "/>" +  "" + this.p.colNames[i] + "(" + this.p.colModel[i].name + ")
");
					}
				}
				var bS  ="<input id='dData' type='button' value='"+p.bSubmit+"'/>";
				var bC  ="<input id='eData' type='button' value='"+p.bCancel+"'/>";
				$(tbl).append("
"+bS+" "+bC+"
");
				p.gbox = "#gbox_"+gID;
				createModal(IDs,tbl,p,$t.grid.hDiv,$t.grid.hDiv);
				//if( p.drag) { DnRModal("#"+IDs.themodal,"#"+IDs.modalhead+" td.modaltext"); }
				$("#dData","#"+dtbl).click(function(e){
					for(i=0;i<$t.p.colModel.length;i++){
						if(!$t.p.colModel[i].hidedlg) { // added from T. Tomov
							if($("#col_" + $t.p.colModel[i].name).attr("checked")) {
								$($t).showCol($t.p.colModel[i].name);
								$("#col_" + $t.p.colModel[i].name).attr("defaultChecked",true); // Added from T. Tomov IE BUG
							} else {
								$($t).hideCol($t.p.colModel[i].name);
								$("#col_" + $t.p.colModel[i].name).attr("defaultChecked",""); // Added from T. Tomov IE BUG
							}
						}
					}
					if(p.ShrinkToFit===true) {
						$($t).setGridWidth($t.grid.width-0.01,true);
					}
					hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:false});
					if (onAfterSubmit) { p.afterSubmitForm($("#"+dtbl)); }
					return false;
				});
				$("#eData", "#"+dtbl).click(function(e){
					hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:false});
					return false;
				});
				$("#dData, #eData","#"+dtbl).addClass('ui-state-default ui-corner-all')
				.css({padding:".2em .5em", cursor: 'pointer'})
				.hover(
				   function(){$(this).addClass('ui-state-hover');},
				   function(){$(this).removeClass('ui-state-hover');}
				);
				if(onBeforeShow) { p.beforeShowForm($("#"+dtbl)); }
				viewModal("#"+IDs.themodal,{gbox:"#gbox_"+gID,jqm:false});
				if(onAfterShow) { p.afterShowForm($("#"+dtbl)); }
			}
		});
	}
});
})(jQuery);<|endoftext|>


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

/**
 * Deploy a simulation to spot.
 *
 * @author Aaron Davis
 */

// The following comment permits node-specific globals (such as process.cwd()) to pass jshint
/* jslint node: true */
'use strict';

// modules
var child_process = require( 'child_process' );
var assert = require( 'assert' );
var fs = require( 'fs' );

// constants
var DEV_SERVER = 'spot.colorado.edu';
var DEV_DIRECTORY = '/htdocs/physics/phet/dev/html/';
var URL_BASE = 'http://www.colorado.edu/physics/phet/dev/html/';
var HTACCESS_TEXT = 'IndexOrderDefault Descending Date\n';
var BUILD_DIR = 'build';
var PACKAGE_JSON = 'package.json';
var DEPENDENCIES_JSON = 'dependencies.json';

/**
 * @param grunt the grunt instance
 * @param simDir the sim directory path
 * @param mkdir set to true to create the sim dir and .htaccess file before copying the version directory
 * @param test set to true disable commit and push, and SCP to a test directory on spot
 */
module.exports = function( grunt, simDir, mkdir, test ) {

  // read the preferences file
  var PREFERENCES_FILE = process.env.HOME + '/.phet/build-local.json';
  assert( fs.existsSync( PREFERENCES_FILE ), 'missing preferences file ' + PREFERENCES_FILE );
  var preferences = grunt.file.readJSON( PREFERENCES_FILE );

  // verify that preferences contains required entries
  assert( preferences.devUsername, 'devUsername is missing from ' + PREFERENCES_FILE );
  assert( preferences.devPassword, 'devPassword is missing from ' + PREFERENCES_FILE );

  // check prerequisite files
  assert( grunt.file.exists( PACKAGE_JSON ), 'Cannot find ' + PACKAGE_JSON );
  assert( grunt.file.exists( BUILD_DIR ), 'Cannot find ' + BUILD_DIR );

  // get the server name and server path if they are in the preferences file, otherwise use defaults
  var server = preferences.devDeployServer || DEV_SERVER;
  var basePath = preferences.devDeployPath || DEV_DIRECTORY;
  if ( test ) {
    basePath += 'ad-tests/';
    URL_BASE += 'ad-tests/';
  }

  // get the sim name and version
  var directory = process.cwd();
  var directoryComponents = directory.split( ( /^win/.test( process.platform ) ) ? '\\' : '/' );
  var sim = directoryComponents[ directoryComponents.length - 1 ];
  var version = grunt.file.readJSON( PACKAGE_JSON ).version;
  var simPath = basePath + sim;
  var versionPath = simPath + '/' + version;

  var done = grunt.task.current.async();

  var finish = function() {
    grunt.log.writeln( 'deployed: ' + URL_BASE + sim + '/' + version + '/' + sim + '_en.html' );
    done();
  };

  /**
   * Exec a command, log stdout and stderr, handle errors
   * @param command
   * @param callback
   */
  var exec = function( command, callback ) {
    grunt.log.writeln( 'Running command: ' + command );
    var execOptions = simDir ? { cwd: simDir } : {};
    child_process.exec( command, execOptions, function( err, stdout, stderr ) {
      if ( stdout ) { grunt.log.writeln( stdout ); }
      if ( stderr ) { grunt.log.writeln( stderr ); }
      assert( !err, 'assertion error running ' + command );
      callback();
    } );
  };

  /**
   * Copy dependencies.json to sim root, commit, and push
   * @param callback
   */
  var commitAndPush = function( callback ) {
    grunt.file.copy( BUILD_DIR + '/' + DEPENDENCIES_JSON, DEPENDENCIES_JSON );
    exec( 'git add ' + DEPENDENCIES_JSON, function() {
      exec( 'git commit --message "updated ' + DEPENDENCIES_JSON + ' for ' + version + ' "', function() {
        exec( 'git push', callback );
      } );
    } );
  };

  /**
   * scp file to dev server, and call commitAndPush if not testing
   */
  var scp = function() {
    exec( 'scp -r ' + BUILD_DIR + ' ' + preferences.devUsername + '@' + server + ':' + versionPath, function() {
      if ( test ) {
        finish();
      }
      else {
        commitAndPush( finish );
      }
    } );
  };

  if ( mkdir ) {
    var sshString = 'ssh ' + preferences.devUsername + '@' + server;
    var mkdirAndCreateHtaccessCommand = ' \'mkdir -p ' + simPath + ' && echo "' + HTACCESS_TEXT + '" > ' + simPath + '/.htaccess\'';
    exec( sshString + mkdirAndCreateHtaccessCommand, scp );
  }
  else {
    scp();
  }
};
<commit_msg>fix bug in deployDev when deploying from build server, see #87<commit_after>// Copyright 2002-2015, University of Colorado Boulder

/**
 * Deploy a simulation to spot.
 *
 * @author Aaron Davis
 */

// The following comment permits node-specific globals (such as process.cwd()) to pass jshint
/* jslint node: true */
'use strict';

// modules
var child_process = require( 'child_process' );
var assert = require( 'assert' );
var fs = require( 'fs' );

// constants
var DEV_SERVER = 'spot.colorado.edu';
var DEV_DIRECTORY = '/htdocs/physics/phet/dev/html/';
var URL_BASE = 'http://www.colorado.edu/physics/phet/dev/html/';
var HTACCESS_TEXT = 'IndexOrderDefault Descending Date\n';
var BUILD_DIR = 'build';
var PACKAGE_JSON = 'package.json';
var DEPENDENCIES_JSON = 'dependencies.json';

/**
 * @param grunt the grunt instance
 * @param simDir the sim directory path
 * @param mkdir set to true to create the sim dir and .htaccess file before copying the version directory
 * @param test set to true disable commit and push, and SCP to a test directory on spot
 */
module.exports = function( grunt, simDir, mkdir, test ) {

  // read the preferences file
  var PREFERENCES_FILE = process.env.HOME + '/.phet/build-local.json';
  assert( fs.existsSync( PREFERENCES_FILE ), 'missing preferences file ' + PREFERENCES_FILE );
  var preferences = grunt.file.readJSON( PREFERENCES_FILE );

  // verify that preferences contains required entries
  assert( preferences.devUsername, 'devUsername is missing from ' + PREFERENCES_FILE );
  assert( preferences.devPassword, 'devPassword is missing from ' + PREFERENCES_FILE );

  // check prerequisite files
  assert( grunt.file.exists( PACKAGE_JSON ), 'Cannot find ' + PACKAGE_JSON );
  assert( grunt.file.exists( BUILD_DIR ), 'Cannot find ' + BUILD_DIR );

  // get the server name and server path if they are in the preferences file, otherwise use defaults
  var server = preferences.devDeployServer || DEV_SERVER;
  var basePath = preferences.devDeployPath || DEV_DIRECTORY;
  if ( test ) {
    basePath += 'ad-tests/';
    URL_BASE += 'ad-tests/';
  }

  // get the sim name and version
  var directory = simDir ? simDir : process.cwd();
  var directoryComponents = directory.split( ( /^win/.test( process.platform ) ) ? '\\' : '/' );
  var sim = directoryComponents[ directoryComponents.length - 1 ];
  var version = grunt.file.readJSON( PACKAGE_JSON ).version;
  var simPath = basePath + sim;
  var versionPath = simPath + '/' + version;

  var done = grunt.task.current.async();

  var finish = function() {
    grunt.log.writeln( 'deployed: ' + URL_BASE + sim + '/' + version + '/' + sim + '_en.html' );
    done();
  };

  /**
   * Exec a command, log stdout and stderr, handle errors
   * @param command
   * @param callback
   */
  var exec = function( command, callback ) {
    grunt.log.writeln( 'Running command: ' + command );
    var execOptions = simDir ? { cwd: simDir } : {};
    child_process.exec( command, execOptions, function( err, stdout, stderr ) {
      if ( stdout ) { grunt.log.writeln( stdout ); }
      if ( stderr ) { grunt.log.writeln( stderr ); }
      assert( !err, 'assertion error running ' + command );
      callback();
    } );
  };

  /**
   * Copy dependencies.json to sim root, commit, and push
   * @param callback
   */
  var commitAndPush = function( callback ) {
    grunt.file.copy( BUILD_DIR + '/' + DEPENDENCIES_JSON, DEPENDENCIES_JSON );
    exec( 'git add ' + DEPENDENCIES_JSON, function() {
      exec( 'git commit --message "updated ' + DEPENDENCIES_JSON + ' for ' + version + ' "', function() {
        exec( 'git push', callback );
      } );
    } );
  };

  /**
   * scp file to dev server, and call commitAndPush if not testing
   */
  var scp = function() {
    exec( 'scp -r ' + BUILD_DIR + ' ' + preferences.devUsername + '@' + server + ':' + versionPath, function() {
      if ( test ) {
        finish();
      }
      else {
        commitAndPush( finish );
      }
    } );
  };

  if ( mkdir ) {
    var sshString = 'ssh ' + preferences.devUsername + '@' + server;
    var mkdirAndCreateHtaccessCommand = ' \'mkdir -p ' + simPath + ' && echo "' + HTACCESS_TEXT + '" > ' + simPath + '/.htaccess\'';
    exec( sshString + mkdirAndCreateHtaccessCommand, scp );
  }
  else {
    scp();
  }
};
<|endoftext|>


<commit_before>Highbrow.SearchDialog = this.Highbrow.SearchDialog = function(hb,conf) {

    "use strict";

    if (! (this instanceof Highbrow.SearchDialog)) throw "called Highbrow.SearchDialog constructor as if it were a function: missing 'new'.";

    var jqd = null; // jquery dialog object.
    var searchCount=0;

    var regexSearch = function(t,term,additionalModifiers){
	var re = new RegExp(term,"g"+additionalModifiers);
	var m;
	while (  m = re.exec(sequence.data) ) {
	    var n = {};
	    n.start=m.index;
	    n.name=m+"";
	    n.stop=m.index+(m+"").length-1;
	    t.notes.push(n);
	}
    };

    var search = function (term,ignoreCase,useRegExp){
	// for now, add a new track with search term
	var t = hb.initTrack();
	var additionalModifiers = "";
	if ( ignoreCase ) {
	    additionalModifiers = "i";
	}
	if ( useRegExp ) {
	    t.name="/" + term + "/"+additionalModifiers;
	    regexSearch(t,term,additionalModifiers);
	} else {
	    t.name="\"" + term + "\"";
	    regexSearch(t,term,additionalModifiers);
	}
	t.id = "search" + searchCount;
	t.type="search";
	searchCount++;
	hb.addTrack(t);
    };

    var init = function(){
	$("#"+hb.prefix + "showSearchDialog").click(function(e) { show() ; e.preventDefault(); });
	initDialog();
    };

    var show = function(){
	jqd.dialog('open');
	return false;
    };

    var initDialog = function(){
	var html ="

Type a term to locate in the text.
";
	html+= "
Your results will be plotted as a new track.
";
	html+="<form>
<input id=\"sb\" type=\"text\" size=\"30\"/>
";
	html+="
Ignore Case?" + hb.cb(true,{"id" : "scase"}) + "
";
	html+="
Regular Expression?" + hb.cb(false,{"id" : "sregexp"}) + "
";
	html+="</form>
";
	jqd = $('

')
	.html(html)
	.dialog({
		autoOpen: false,
		title: 'Search Highbrow Text',
		height: 290,
		width: 300,
		buttons:
		{
		    "Search": function()  {
			search($("#sb").val(),hb.cbChecked("#scase"),hb.cbChecked("#sregexp"));
		    }
		}
	    });
    };

    init();

};<commit_msg>fixed return key behavior in search dialog<commit_after>Highbrow.SearchDialog = this.Highbrow.SearchDialog = function(hb,conf) {

    "use strict";

    if (! (this instanceof Highbrow.SearchDialog)) throw "called Highbrow.SearchDialog constructor as if it were a function: missing 'new'.";

    var jqd = null; // jquery dialog object.
    var searchCount=0;

    var regexSearch = function(t,term,additionalModifiers){
	var re = new RegExp(term,"g"+additionalModifiers);
	var m;
	while (  m = re.exec(sequence.data) ) {
	    var n = {};
	    n.start=m.index;
	    n.name=m+"";
	    n.stop=m.index+(m+"").length-1;
	    t.notes.push(n);
	}
    };

    var search = function (term,ignoreCase,useRegExp){
	// for now, add a new track with search term
	var t = hb.initTrack();
	var additionalModifiers = "";
	if ( ignoreCase ) {
	    additionalModifiers = "i";
	}
	if ( useRegExp ) {
	    t.name="/" + term + "/"+additionalModifiers;
	    regexSearch(t,term,additionalModifiers);
	} else {
	    t.name="\"" + term + "\"";
	    regexSearch(t,term,additionalModifiers);
	}
	t.id = "search" + searchCount;
	t.type="search";
	searchCount++;
	hb.addTrack(t);
    };

    var init = function(){
	$("#"+hb.prefix + "showSearchDialog").click(function(e) { show() ; e.preventDefault(); });
	initDialog();
    };

    var show = function(){
	jqd.dialog('open');
	return false;
    };

    var initDialog = function(){
	var searchDialogId =  hb.prefix+'searchDialog';
	var searchDialogFormId  = searchDialogId + "Form";
	var searchDialogInputTextId  = searchDialogFormId + "InputText";
	var searchDialogIgnoreCaseId = searchDialogFormId + "IgnoreCase";
	var searchDialogRegexId = searchDialogFormId + "Regex";

	$('body').on("submit",'#'+searchDialogFormId,function(event){
	    event.preventDefault();
	    search($('#'+searchDialogInputTextId).val(),hb.cbChecked('#'+searchDialogIgnoreCaseId),hb.cbChecked('#'+searchDialogRegexId));

	});

	var html ="

Type a term to locate in the text.
";
	html+= '
Your results will be plotted as a new track.
';
	html+='<form id="'+ searchDialogFormId +'">
<input id="' + searchDialogInputTextId + '" type="text" size="30"/>
';
	html+="
Ignore Case?" + hb.cb(true,{"id" : searchDialogIgnoreCaseId}) + "
";
	html+="
Regular Expression?" + hb.cb(false,{"id" : searchDialogRegexId}) + "
";
	html+="</form>
";
	jqd = $('

')

	.html(html)
	.dialog({
		autoOpen: false,
		title: 'Search Highbrow Text',
		height: 290,
		width: 300,
		buttons:
		{
		    "Search": function()  {
			$('#'+searchDialogFormId).submit();

		    }

		}
	    });

    };

    init();

};<|endoftext|>