<commit_before>import { h, ref, computed, inject, onBeforeUnmount, onMounted, withDirectives, getCurrentInstance } from 'vue'

import QIcon from '../icon/QIcon.js'

import Ripple from '../../directives/Ripple.js'

import { hMergeSlot } from '../../utils/private/render.js'
import { isKeyCode, shouldIgnoreKey } from '../../utils/private/key-composition.js'
import { tabsKey } from '../../utils/private/symbols.js'
import { stopAndPrevent } from '../../utils/event.js'

let uid = 0

export const useTabEmits = [ 'click', 'keydown' ]

export const useTabProps = {
  icon: String,
  label: [ Number, String ],

  alert: [ Boolean, String ],
  alertIcon: String,

  name: {
    type: [ Number, String ],
    default: () => `t_${ uid++ }`
  },

  noCaps: Boolean,

  tabindex: [ String, Number ],
  disable: Boolean,

  contentClass: String,

  ripple: {
    type: [ Boolean, Object ],
    default: true
  }
}

export default function (props, slots, emit, routerProps) {
  const $tabs = inject(tabsKey, () => {
    console.error('QTab/QRouteTab component needs to be child of QTabs')
  })

  const { proxy } = getCurrentInstance()

  const blurTargetRef = ref(null)
  const rootRef = ref(null)
  const tabIndicatorRef = ref(null)

  const ripple = computed(() => (
    props.disable === true || props.ripple === false
      ? false
      : Object.assign(
        { keyCodes: [ 13, 32 ], early: true },
        props.ripple === true ? {} : props.ripple
      )
  ))

  const isActive = computed(() => $tabs.currentModel.value === props.name)

  const classes = computed(() =>
    'q-tab relative-position self-stretch flex flex-center text-center'
    + (
      isActive.value === true
        ? (
            ' q-tab--active'
            + ($tabs.tabProps.value.activeClass ? ' ' + $tabs.tabProps.value.activeClass : '')
            + ($tabs.tabProps.value.activeColor ? ` text-${ $tabs.tabProps.value.activeColor }` : '')
            + ($tabs.tabProps.value.activeBgColor ? ` bg-${ $tabs.tabProps.value.activeBgColor }` : '')
          )
        : ' q-tab--inactive'
    )
    + (props.icon && props.label && $tabs.tabProps.value.inlineLabel === false ? ' q-tab--full' : '')
    + (props.noCaps === true || $tabs.tabProps.value.noCaps === true ? ' q-tab--no-caps' : '')
    + (props.disable === true ? ' disabled' : ' q-focusable q-hoverable cursor-pointer')
    + (routerProps !== void 0 && routerProps.linkClass.value !== '' ? ` ${ routerProps.linkClass.value }` : '')
  )

  const innerClass = computed(() =>
    'q-tab__content self-stretch flex-center relative-position q-anchor--skip non-selectable '
    + ($tabs.tabProps.value.inlineLabel === true ? 'row no-wrap q-tab__content--inline' : 'column')
    + (props.contentClass !== void 0 ? ` ${ props.contentClass }` : '')
  )

  const tabIndex = computed(() => (
    props.disable === true || $tabs.hasFocus.value === true
      ? -1
      : props.tabindex || 0
  ))

  function onClick (e, keyboard) {
    keyboard !== true && blurTargetRef.value !== null && blurTargetRef.value.focus()

    if (props.disable !== true) {
      let go

      if (routerProps !== void 0) {
        if (routerProps.hasRouterLink.value === true) {
          go = () => {
            e.__qNavigate = true
            $tabs.avoidRouteWatcher = true

            const res = routerProps.navigateToRouterLink(e)

            if (res === false) {
              $tabs.avoidRouteWatcher = false
            }
            else {
              res.then(err => {
                $tabs.avoidRouteWatcher = false

                if (err === void 0) {
                  $tabs.updateModel({ name: props.name, fromRoute: true })
                }
              })
            }
          }
        }
        else {
          emit('click', e)
          return
        }
      }
      else {
        go = () => {
          $tabs.updateModel({ name: props.name, fromRoute: false })
        }
      }

      emit('click', e, go)
      e.defaultPrevented !== true && go()
    }
  }

  function onKeydown (e) {
    if (isKeyCode(e, [ 13, 32 ])) {
      onClick(e, true)
    }
    else if (shouldIgnoreKey(e) !== true && e.keyCode >= 35 && e.keyCode <= 40) {
      $tabs.onKbdNavigate(e.keyCode, proxy.$el) === true && stopAndPrevent(e)
    }
    emit('keydown', e)
  }

  function getContent () {
    const
      narrow = $tabs.tabProps.value.narrowIndicator,
      content = [],
      indicator = h('div', {
        ref: tabIndicatorRef,
        class: [
          'q-tab__indicator',
          $tabs.tabProps.value.indicatorClass
        ]
      })

    props.icon !== void 0 && content.push(
      h(QIcon, {
        class: 'q-tab__icon',
        name: props.icon
      })
    )

    props.label !== void 0 && content.push(
      h('div', { class: 'q-tab__label' }, props.label)
    )

    props.alert !== false && content.push(
      props.alertIcon !== void 0
        ? h(QIcon, {
          class: 'q-tab__alert-icon',
          color: props.alert !== true
            ? props.alert
            : void 0,
          name: props.alertIcon
        })
        : h('div', {
          class: 'q-tab__alert'
            + (props.alert !== true ? ` text-${ props.alert }` : '')
        })
    )

    narrow === true && content.push(indicator)

    const node = [
      h('div', { class: 'q-focus-helper', tabindex: -1, ref: blurTargetRef }),
      h('div', { class: innerClass.value }, hMergeSlot(slots.default, content))
    ]

    narrow === false && node.push(indicator)

    return node
  }

  const tabData = {
    name: computed(() => props.name),
    rootRef,
    tabIndicatorRef,
    routerProps
  }

  onBeforeUnmount(() => {
    $tabs.unregisterTab(tabData)
    $tabs.recalculateScroll()
  })

  onMounted(() => {
    $tabs.registerTab(tabData)
    $tabs.recalculateScroll()
  })

  function renderTab (tag, customData) {
    const data = {
      ref: rootRef,
      class: classes.value,
      tabindex: tabIndex.value,
      role: 'tab',
      'aria-selected': isActive.value === true ? 'true' : 'false',
      'aria-disabled': props.disable === true ? 'true' : void 0,
      onClick,
      onKeydown,
      ...customData
    }

    return withDirectives(
      h(tag, data, getContent()),
      [ [ Ripple, ripple.value ] ]
    )
  }

  return { renderTab, $tabs }
}
<commit_msg>feat(QTabs): check if metaKey or altKey are pressed before tabs navigation (#13812)<commit_after>import { h, ref, computed, inject, onBeforeUnmount, onMounted, withDirectives, getCurrentInstance } from 'vue'

import QIcon from '../icon/QIcon.js'

import Ripple from '../../directives/Ripple.js'

import { hMergeSlot } from '../../utils/private/render.js'
import { isKeyCode, shouldIgnoreKey } from '../../utils/private/key-composition.js'
import { tabsKey } from '../../utils/private/symbols.js'
import { stopAndPrevent } from '../../utils/event.js'

let uid = 0

export const useTabEmits = [ 'click', 'keydown' ]

export const useTabProps = {
  icon: String,
  label: [ Number, String ],

  alert: [ Boolean, String ],
  alertIcon: String,

  name: {
    type: [ Number, String ],
    default: () => `t_${ uid++ }`
  },

  noCaps: Boolean,

  tabindex: [ String, Number ],
  disable: Boolean,

  contentClass: String,

  ripple: {
    type: [ Boolean, Object ],
    default: true
  }
}

export default function (props, slots, emit, routerProps) {
  const $tabs = inject(tabsKey, () => {
    console.error('QTab/QRouteTab component needs to be child of QTabs')
  })

  const { proxy } = getCurrentInstance()

  const blurTargetRef = ref(null)
  const rootRef = ref(null)
  const tabIndicatorRef = ref(null)

  const ripple = computed(() => (
    props.disable === true || props.ripple === false
      ? false
      : Object.assign(
        { keyCodes: [ 13, 32 ], early: true },
        props.ripple === true ? {} : props.ripple
      )
  ))

  const isActive = computed(() => $tabs.currentModel.value === props.name)

  const classes = computed(() =>
    'q-tab relative-position self-stretch flex flex-center text-center'
    + (
      isActive.value === true
        ? (
            ' q-tab--active'
            + ($tabs.tabProps.value.activeClass ? ' ' + $tabs.tabProps.value.activeClass : '')
            + ($tabs.tabProps.value.activeColor ? ` text-${ $tabs.tabProps.value.activeColor }` : '')
            + ($tabs.tabProps.value.activeBgColor ? ` bg-${ $tabs.tabProps.value.activeBgColor }` : '')
          )
        : ' q-tab--inactive'
    )
    + (props.icon && props.label && $tabs.tabProps.value.inlineLabel === false ? ' q-tab--full' : '')
    + (props.noCaps === true || $tabs.tabProps.value.noCaps === true ? ' q-tab--no-caps' : '')
    + (props.disable === true ? ' disabled' : ' q-focusable q-hoverable cursor-pointer')
    + (routerProps !== void 0 && routerProps.linkClass.value !== '' ? ` ${ routerProps.linkClass.value }` : '')
  )

  const innerClass = computed(() =>
    'q-tab__content self-stretch flex-center relative-position q-anchor--skip non-selectable '
    + ($tabs.tabProps.value.inlineLabel === true ? 'row no-wrap q-tab__content--inline' : 'column')
    + (props.contentClass !== void 0 ? ` ${ props.contentClass }` : '')
  )

  const tabIndex = computed(() => (
    props.disable === true || $tabs.hasFocus.value === true
      ? -1
      : props.tabindex || 0
  ))

  function onClick (e, keyboard) {
    keyboard !== true && blurTargetRef.value !== null && blurTargetRef.value.focus()

    if (props.disable !== true) {
      let go

      if (routerProps !== void 0) {
        if (routerProps.hasRouterLink.value === true) {
          go = () => {
            e.__qNavigate = true
            $tabs.avoidRouteWatcher = true

            const res = routerProps.navigateToRouterLink(e)

            if (res === false) {
              $tabs.avoidRouteWatcher = false
            }
            else {
              res.then(err => {
                $tabs.avoidRouteWatcher = false

                if (err === void 0) {
                  $tabs.updateModel({ name: props.name, fromRoute: true })
                }
              })
            }
          }
        }
        else {
          emit('click', e)
          return
        }
      }
      else {
        go = () => {
          $tabs.updateModel({ name: props.name, fromRoute: false })
        }
      }

      emit('click', e, go)
      e.defaultPrevented !== true && go()
    }
  }

  function onKeydown (e) {
    if (isKeyCode(e, [ 13, 32 ])) {
      onClick(e, true)
    }
    else if (
      shouldIgnoreKey(e) !== true
      && e.keyCode >= 35
      && e.keyCode <= 40
      && e.altKey !== true
      && e.metaKey !== true
    ) {
      $tabs.onKbdNavigate(e.keyCode, proxy.$el) === true && stopAndPrevent(e)
    }

    emit('keydown', e)
  }

  function getContent () {
    const
      narrow = $tabs.tabProps.value.narrowIndicator,
      content = [],
      indicator = h('div', {
        ref: tabIndicatorRef,
        class: [
          'q-tab__indicator',
          $tabs.tabProps.value.indicatorClass
        ]
      })

    props.icon !== void 0 && content.push(
      h(QIcon, {
        class: 'q-tab__icon',
        name: props.icon
      })
    )

    props.label !== void 0 && content.push(
      h('div', { class: 'q-tab__label' }, props.label)
    )

    props.alert !== false && content.push(
      props.alertIcon !== void 0
        ? h(QIcon, {
          class: 'q-tab__alert-icon',
          color: props.alert !== true
            ? props.alert
            : void 0,
          name: props.alertIcon
        })
        : h('div', {
          class: 'q-tab__alert'
            + (props.alert !== true ? ` text-${ props.alert }` : '')
        })
    )

    narrow === true && content.push(indicator)

    const node = [
      h('div', { class: 'q-focus-helper', tabindex: -1, ref: blurTargetRef }),
      h('div', { class: innerClass.value }, hMergeSlot(slots.default, content))
    ]

    narrow === false && node.push(indicator)

    return node
  }

  const tabData = {
    name: computed(() => props.name),
    rootRef,
    tabIndicatorRef,
    routerProps
  }

  onBeforeUnmount(() => {
    $tabs.unregisterTab(tabData)
    $tabs.recalculateScroll()
  })

  onMounted(() => {
    $tabs.registerTab(tabData)
    $tabs.recalculateScroll()
  })

  function renderTab (tag, customData) {
    const data = {
      ref: rootRef,
      class: classes.value,
      tabindex: tabIndex.value,
      role: 'tab',
      'aria-selected': isActive.value === true ? 'true' : 'false',
      'aria-disabled': props.disable === true ? 'true' : void 0,
      onClick,
      onKeydown,
      ...customData
    }

    return withDirectives(
      h(tag, data, getContent()),
      [ [ Ripple, ripple.value ] ]
    )
  }

  return { renderTab, $tabs }
}
<|endoftext|>


<commit_before>/// <reference name="MicrosoftAjax.js" />
/// <reference name="dnn.controls.js" assembly="DotNetNuke.WebControls" />
/// <reference name="dnn.js" assembly="DotNetNuke.WebUtility" />
/// <reference name="dnn.dom.positioning.js" assembly="DotNetNuke.WebUtility" />
/// <reference name="dnn.xmlhttp.js" assembly="DotNetNuke.WebUtility" />

Type.registerNamespace('dnn.controls');

dnn.extend(dnn.controls, {
    initLabelEdit: function (ctl)
    {
	    if (ctl)
	    {
		    var lbl = new dnn.controls.DNNLabelEdit(ctl);
		    lbl.initialize();
		    return lbl;
	    }
    }
});

//------- Constructor -------//
dnn.controls.DNNLabelEdit = function (o)
{
	dnn.controls.DNNLabelEdit.initializeBase(this, [o]);

    this.control = this.container;//backwards compat

	this.editWrapper = null;	//stores dnn wrapper for abstracted edit control
	this.editContainer = null; //stores container of the control (necessary for iframe controls)
	this.editControl = null; //stores reference to underlying edit control (input, span, textarea)
	this.prevText = '';

	this.onblurSave = (this.getProp('blursave', '1') == '1');

	this.toolbarId = this.getProp('tbId', '');
	this.nsPrefix = this.getProp('nsPrefix', '');
	this.toolbarEventName = this.getProp('tbEvent', 'onmousemove');
	this.toolbar = null;
	//this.scriptPath = dnn.dom.getScriptPath();
	//var oThisScript = dnn.dom.getScript('dnn.controls.dnnlabeledit.js');
	//if (oThisScript)
	//	this.scriptPath = oThisScript.src.replace('dnn.controls.dnnlabeledit.js', '');

	this.css = o.className;
	this.cssEdit = this.getProp('cssEdit', '');
	this.cssWork = this.getProp('cssWork', '');
	this.cssOver = this.getProp('cssOver', '');
	this.sysImgPath = this.getProp('sysimgpath', '');
	this.callBack = this.getProp('callback', '');
	this.callBackStatFunc = this.getProp('callbackSF', '');
	if (this.callBackStatFunc.length > 0)
	    this.add_handler('callBackStatus', eval(this.callBackStatFunc));

	this.beforeSaveFunc = this.getProp('beforeSaveF', '');
	if (this.beforeSaveFunc.length > 0)
	    this.add_handler('beforeSave', eval(this.beforeSaveFunc));

	this.eventName = this.getProp('eventName', 'onclick');
	//this.editEnabled = dnn.dom.getAttr(o, 'editEnabled', '1') == '1';
	this.multiLineEnabled = this.getProp('multiline', '0') == '1';
	this.saveOnEnter = this.getProp('saveonenter', '1') == '1';
	this.richTextEnabled = this.getProp('richtext', '0') == '1';
	this.supportsCE = (document.body.contentEditable != null);
	if (dnn.dom.browser.isType(dnn.dom.browser.Safari) || dnn.dom.browser.isType(dnn.dom.browser.Opera))
		this.supportsCE = false;//Safari content editable still buggy...
	this.supportsRichText = (this.supportsCE || (dnn.dom.browser.isType(dnn.dom.browser.Mozilla) && navigator.productSub >= '20050111'));	//i belive firefox only works well with 1.5 or later, need a better way to detect this!

	if (this.eventName != 'none')
	    this.addHandlers(o, this.getDynamicEventObject(this._getEventName(this.eventName), this.performEdit), this);

	if (this.toolbarId.length > 0)
	    this.addHandlers(o, this.getDynamicEventObject(this._getEventName(this.toolbarEventName), this.showToolBar), this);

    this.addHandlers(o, {'mousemove': this.mouseMove,
                        'mouseout': this.mouseOut}, this);

    this._toolbarActionDelegate = dnn.createDelegate(this, this.toolbarAction);
    this._initToolbarDelegate = dnn.createDelegate(this, this.initToolbar);
    this._performEditDelegate = dnn.createDelegate(this, this.performEdit);
}

dnn.controls.DNNLabelEdit.prototype =
{

    isEditMode: function()
    {
        return (this.container.style.display != '')
    },

    initToolbar: function()
    {
        if (this.toolbar == null)
        {
            var status = dnn.dom.scriptStatus('dnn.controls.dnntoolbar.js');
            if (status == 'complete')
            {
                this.toolbar = new dnn.controls.DNNToolBar(this.ns);
                this.toolbar.loadDefinition(this.toolbarId, this.nsPrefix, this.container, this.container.parentNode, this.container, this._toolbarActionDelegate);
                this.handleToolbarDisplay();
            }
            else if (status == '')	//not loaded
                dnn.dom.loadScript(dnn.dom.getScriptPath() + 'dnn.controls.dnntoolbar.js', '', this._initToolbarDelegate);
        }

    },

    toolbarAction: function(btn, src)
    {
        var action = btn.clickAction;
        if (action == 'edit')
            this.performEdit();
        else if (action == 'save')
        {
            this.persistEdit();
            this.toolbar.hide();
        }
        else if (action == 'cancel')
        {
            this.cancelEdit();
            this.toolbar.hide();
        }
        else if (this.isFormatButton(action))
        {
            if (this.editWrapper)
            {
                var link;
                if (action == 'createlink' && dnn.dom.browser.isType(dnn.dom.browser.InternetExplorer) == false)
                    link = prompt(btn.tooltip);

                this.editWrapper.focus();
                this.editWrapper.execCommand(action, null, link);
            }
        }

    },

    performEdit: function()
    {
        if (this.toolbar)
            this.toolbar.hide();

        this.initEditWrapper();
        if (this.editContainer != null)
        {
            //this.editContainer.style.height = (dnn.dom.positioning.elementHeight(this.container) + 4) + 'px';
            //var dims = new dnn.dom.positioning.dims(this.container.parentNode);
            //this.editContainer.style.width = (dims.w - dims.l) + 'px';
            //this.editContainer.style.width = dnn.dom.positioning.elementWidth(this.container.parentNode) + 'px' //'100%';
            this.editContainer.style.width = '100%';
            this.editContainer.style.display = '';
            //this.editContainer.style.visibility = '';	//firefox workaround... can't do display none
            this.editContainer.style.overflow = 'auto';
            this.editContainer.style.overflowX = 'hidden';

            this.prevText = this.container.innerHTML;
            if (dnn.dom.browser.isType(dnn.dom.browser.Safari) && this.container.innerText)		//safari gets strange chars... use innerText
                this.prevText = this.container.innerText;
            this.editWrapper.setText(this.prevText);
            this.initEditControl();
            this.container.style.display = 'none';
            this.handleToolbarDisplay();

            var arg = new Sys.CancelEventArgs();
            this.invoke_handler('beforeEdit', arg);
            if (arg.get_cancel())
            {
                this.cancelEdit();
                return;
            }

        }
    },

    showToolBar: function()
    {
        this.initToolbar();
        if (this.toolbar)
            this.toolbar.show(true);
    },

    mouseMove: function(e)
    {
        if (this.toolbarId.length > 0 && this.toolbarEventName == 'onmousemove')
            this.showToolBar();
        this.container.className = this.css + ' ' + this.cssOver;
    },

    mouseOut: function()
    {
        if (this.toolbar)
            this.toolbar.beginHide();
        this.container.className = this.css;
    },

    initEditWrapper: function()
    {
        if (this.editWrapper == null)
        {
            var richText = (this.richTextEnabled && this.supportsRichText);
            var script = (richText ? 'dnn.controls.dnnrichtext.js' : 'dnn.controls.dnninputtext.js');

            var status = dnn.dom.scriptStatus(script);
            if (status == 'complete')
            {
                var txt;
                if (this.richTextEnabled && this.supportsRichText)
                {
                    var func = dnn.dom.getObjMethRef(this, 'initEditControl');
                    txt = new dnn.controls.DNNRichText(func);
                }
                else
                    txt = new dnn.controls.DNNInputText(this.multiLineEnabled);

                this.editWrapper = txt;
                this.editContainer = this.editWrapper.container;
                this.container.parentNode.insertBefore(this.editContainer, this.container);
                if (this.richTextEnabled && this.supportsCE)	//control is instantly available (not an iframe)
                    this.initEditControl();
            }
            else if (status == '') //not loaded
                dnn.dom.loadScript(dnn.dom.getScriptPath() + script, '', this._performEditDelegate);
        }
    },

    initEditControl: function()
    {
        if (this.editWrapper.initialized)
        {
            this.editControl = this.editWrapper.control;
            this.editControl.className = this.container.className + ' ' + this.cssEdit;
            this.editWrapper.focus();
            if (this.editWrapper.loaded == false)
            {
                var eventObj = { keypress: this.handleKeyPress,
                    mousemove: this.mouseMove,
                    mouseout: this.mouseOut
                };

                if (this.onblurSave)
                    eventObj.blur = this.persistEdit;

                if (this.editWrapper.supportsCE || this.editWrapper.isRichText == false)	//if browser supports contentEditable or is a simple INPUT control
                    this.addHandlers(this.editControl, eventObj, this);
                else	//IFRAME event handlers
                    this.addHandlers(this.editContainer.contentWindow.document, eventObj, this);

                this.editWrapper.loaded = true;
            }
        }
    },

    persistEdit: function()
    {
        if (this.editWrapper.getText() != this.prevText)
        {
            if (this.invoke_compatHandler('beforeSave', null, this))
            {
                this.editControl.className = this.container.className + ' ' + this.cssWork;
                eval(this.callBack.replace('[TEXT]', dnn.escapeForEval(this.editWrapper.getText())));
            }
        }
        else
            this.showLabel();
    },

    cancelEdit: function()
    {
        this.editWrapper.setText(this.prevText);
        this.showLabel();
    },

    callBackStatus: function(result, ctx, req)
    {
        var lbl = ctx;
        lbl.invoke_compatHandler('callBackStatus', result, ctx, req);
    },

    callBackSuccess: function(result, ctx, req)
    {
        ctx.callBackStatus(result, ctx);
        ctx.invoke_handler('callBackSuccess', new dnn.controls.DNNCallbackEventArgs(result, ctx, req));
        ctx.showLabel();
	    ctx.flashLabel();
    },

    //obsolete
    raiseEvent: function(sFunc, evt, element)
    {
        if (this[sFunc].length > 0)
        {
            var ptr = eval(this[sFunc]);
            return ptr(evt, element) != false;
        }
        return true;
    },

    handleToolbarDisplay: function()
    {
        if (this.toolbar)
        {
            var inEdit = this.isEditMode();
            var btn;
            for (var key in this.toolbar.buttons)
            {
                btn = this.toolbar.buttons[key];
                if (typeof btn == 'function')	//safeguard against other js frameworks
                    continue;

	            if (key == 'edit') {
	            	btn.visible = !inEdit;
		            if (btn.visible) {
			            this.toolbar.css = this.toolbar.css.replace(" editMode", "");
		            } else {
			            this.toolbar.css = this.toolbar.css + " editMode";
		            }
	            } else if (this.isFormatButton(key))
		            btn.visible = (inEdit && this.editWrapper && this.editWrapper.isRichText);
	            else
		            btn.visible = inEdit;

            }
            this.toolbar.refresh();
        }
    },

    isFormatButton: function(key)
    {
        return '~bold~italic~underline~justifyleft~justifycenter~justifyright~insertorderedlist~insertunorderedlist~outdent~indent~createlink~'.indexOf('~' + key + '~') > -1;
    },

    showLabel: function()
    {
        this.container.innerHTML = this.editWrapper.getText();
        this.container.style.display = '';
        this.container.className = this.css;
        //this.editContainer.style.width = 0; //firefox workaround
        //this.editContainer.style.visibility = 'hidden';	//firefox workaround
        this.editContainer.style.display = 'none';
        this.handleToolbarDisplay();
    },

    flashLabel: function () {
    	var handler = this;
	    this.container.style.backgroundColor = "#fffacd";
	    setTimeout(function () {
		    handler.container.style.backgroundColor = "#fffff0";
		    setTimeout(function () {
			    handler.container.style.backgroundColor = "transparent";
            }, 300);
        }, 2500);
	},

    callBackFail: function(result, ctx, req)
    {
        ctx.invoke_handler('callBackFail', new dnn.controls.DNNCallbackEventArgs(result, ctx, req));
        ctx.cancelEdit();
    },

    handleKeyPress: function(e)
    {
        if (e.charCode == KEY_RETURN && this.editWrapper.supportsMultiLine == false)
        {
            if (this.saveOnEnter)
                this.persistEdit();
            e.preventDefault();
        }
        else if (e.charCode == KEY_ESCAPE)
        {
            this.cancelEdit();
            e.preventDefault();
        }
    },

    dispose: function()
    {
        this._toolbarActionDelegate = null;
        this._initToolbarDelegate = null;
        this._performEditDelegate = null;
        dnn.controls.DNNLabelEdit.callBaseMethod(this, 'dispose');
    }

}

dnn.controls.DNNLabelEdit.registerClass('dnn.controls.DNNLabelEdit', dnn.controls.control);<commit_msg>DNN-7748: Updated showToolBar method so that the edit button won't be automatically hidden after mousemove<commit_after>/// <reference name="MicrosoftAjax.js" />
/// <reference name="dnn.controls.js" assembly="DotNetNuke.WebControls" />
/// <reference name="dnn.js" assembly="DotNetNuke.WebUtility" />
/// <reference name="dnn.dom.positioning.js" assembly="DotNetNuke.WebUtility" />
/// <reference name="dnn.xmlhttp.js" assembly="DotNetNuke.WebUtility" />

Type.registerNamespace('dnn.controls');

dnn.extend(dnn.controls, {
    initLabelEdit: function (ctl)
    {
	    if (ctl)
	    {
		    var lbl = new dnn.controls.DNNLabelEdit(ctl);
		    lbl.initialize();
		    return lbl;
	    }
    }
});

//------- Constructor -------//
dnn.controls.DNNLabelEdit = function (o)
{
	dnn.controls.DNNLabelEdit.initializeBase(this, [o]);

    this.control = this.container;//backwards compat

	this.editWrapper = null;	//stores dnn wrapper for abstracted edit control
	this.editContainer = null; //stores container of the control (necessary for iframe controls)
	this.editControl = null; //stores reference to underlying edit control (input, span, textarea)
	this.prevText = '';

	this.onblurSave = (this.getProp('blursave', '1') == '1');

	this.toolbarId = this.getProp('tbId', '');
	this.nsPrefix = this.getProp('nsPrefix', '');
	this.toolbarEventName = this.getProp('tbEvent', 'onmousemove');
	this.toolbar = null;
	//this.scriptPath = dnn.dom.getScriptPath();
	//var oThisScript = dnn.dom.getScript('dnn.controls.dnnlabeledit.js');
	//if (oThisScript)
	//	this.scriptPath = oThisScript.src.replace('dnn.controls.dnnlabeledit.js', '');

	this.css = o.className;
	this.cssEdit = this.getProp('cssEdit', '');
	this.cssWork = this.getProp('cssWork', '');
	this.cssOver = this.getProp('cssOver', '');
	this.sysImgPath = this.getProp('sysimgpath', '');
	this.callBack = this.getProp('callback', '');
	this.callBackStatFunc = this.getProp('callbackSF', '');
	if (this.callBackStatFunc.length > 0)
	    this.add_handler('callBackStatus', eval(this.callBackStatFunc));

	this.beforeSaveFunc = this.getProp('beforeSaveF', '');
	if (this.beforeSaveFunc.length > 0)
	    this.add_handler('beforeSave', eval(this.beforeSaveFunc));

	this.eventName = this.getProp('eventName', 'onclick');
	//this.editEnabled = dnn.dom.getAttr(o, 'editEnabled', '1') == '1';
	this.multiLineEnabled = this.getProp('multiline', '0') == '1';
	this.saveOnEnter = this.getProp('saveonenter', '1') == '1';
	this.richTextEnabled = this.getProp('richtext', '0') == '1';
	this.supportsCE = (document.body.contentEditable != null);
	if (dnn.dom.browser.isType(dnn.dom.browser.Safari) || dnn.dom.browser.isType(dnn.dom.browser.Opera))
		this.supportsCE = false;//Safari content editable still buggy...
	this.supportsRichText = (this.supportsCE || (dnn.dom.browser.isType(dnn.dom.browser.Mozilla) && navigator.productSub >= '20050111'));	//i belive firefox only works well with 1.5 or later, need a better way to detect this!

	if (this.eventName != 'none')
	    this.addHandlers(o, this.getDynamicEventObject(this._getEventName(this.eventName), this.performEdit), this);

	if (this.toolbarId.length > 0)
	    this.addHandlers(o, this.getDynamicEventObject(this._getEventName(this.toolbarEventName), this.showToolBar), this);

    this.addHandlers(o, {'mousemove': this.mouseMove,
                        'mouseout': this.mouseOut}, this);

    this._toolbarActionDelegate = dnn.createDelegate(this, this.toolbarAction);
    this._initToolbarDelegate = dnn.createDelegate(this, this.initToolbar);
    this._performEditDelegate = dnn.createDelegate(this, this.performEdit);
}

dnn.controls.DNNLabelEdit.prototype =
{

    isEditMode: function()
    {
        return (this.container.style.display != '')
    },

    initToolbar: function()
    {
        if (this.toolbar == null)
        {
            var status = dnn.dom.scriptStatus('dnn.controls.dnntoolbar.js');
            if (status == 'complete')
            {
                this.toolbar = new dnn.controls.DNNToolBar(this.ns);
                this.toolbar.loadDefinition(this.toolbarId, this.nsPrefix, this.container, this.container.parentNode, this.container, this._toolbarActionDelegate);
                this.handleToolbarDisplay();
            }
            else if (status == '')	//not loaded
                dnn.dom.loadScript(dnn.dom.getScriptPath() + 'dnn.controls.dnntoolbar.js', '', this._initToolbarDelegate);
        }

    },

    toolbarAction: function(btn, src)
    {
        var action = btn.clickAction;
        if (action == 'edit')
            this.performEdit();
        else if (action == 'save')
        {
            this.persistEdit();
            this.toolbar.hide();
        }
        else if (action == 'cancel')
        {
            this.cancelEdit();
            this.toolbar.hide();
        }
        else if (this.isFormatButton(action))
        {
            if (this.editWrapper)
            {
                var link;
                if (action == 'createlink' && dnn.dom.browser.isType(dnn.dom.browser.InternetExplorer) == false)
                    link = prompt(btn.tooltip);

                this.editWrapper.focus();
                this.editWrapper.execCommand(action, null, link);
            }
        }

    },

    performEdit: function()
    {
        if (this.toolbar)
            this.toolbar.hide();

        this.initEditWrapper();
        if (this.editContainer != null)
        {
            //this.editContainer.style.height = (dnn.dom.positioning.elementHeight(this.container) + 4) + 'px';
            //var dims = new dnn.dom.positioning.dims(this.container.parentNode);
            //this.editContainer.style.width = (dims.w - dims.l) + 'px';
            //this.editContainer.style.width = dnn.dom.positioning.elementWidth(this.container.parentNode) + 'px' //'100%';
            this.editContainer.style.width = '100%';
            this.editContainer.style.display = '';
            //this.editContainer.style.visibility = '';	//firefox workaround... can't do display none
            this.editContainer.style.overflow = 'auto';
            this.editContainer.style.overflowX = 'hidden';

            this.prevText = this.container.innerHTML;
            if (dnn.dom.browser.isType(dnn.dom.browser.Safari) && this.container.innerText)		//safari gets strange chars... use innerText
                this.prevText = this.container.innerText;
            this.editWrapper.setText(this.prevText);
            this.initEditControl();
            this.container.style.display = 'none';
            this.handleToolbarDisplay();

            var arg = new Sys.CancelEventArgs();
            this.invoke_handler('beforeEdit', arg);
            if (arg.get_cancel())
            {
                this.cancelEdit();
                return;
            }

        }
    },

    showToolBar: function()
    {
        this.initToolbar();
        if (this.toolbar)
            this.toolbar.show(false);
    },

    mouseMove: function(e)
    {
        if (this.toolbarId.length > 0 && this.toolbarEventName == 'onmousemove')
            this.showToolBar();
        this.container.className = this.css + ' ' + this.cssOver;
    },

    mouseOut: function()
    {
        if (this.toolbar)
            this.toolbar.beginHide();
        this.container.className = this.css;
    },

    initEditWrapper: function()
    {
        if (this.editWrapper == null)
        {
            var richText = (this.richTextEnabled && this.supportsRichText);
            var script = (richText ? 'dnn.controls.dnnrichtext.js' : 'dnn.controls.dnninputtext.js');

            var status = dnn.dom.scriptStatus(script);
            if (status == 'complete')
            {
                var txt;
                if (this.richTextEnabled && this.supportsRichText)
                {
                    var func = dnn.dom.getObjMethRef(this, 'initEditControl');
                    txt = new dnn.controls.DNNRichText(func);
                }
                else
                    txt = new dnn.controls.DNNInputText(this.multiLineEnabled);

                this.editWrapper = txt;
                this.editContainer = this.editWrapper.container;
                this.container.parentNode.insertBefore(this.editContainer, this.container);
                if (this.richTextEnabled && this.supportsCE)	//control is instantly available (not an iframe)
                    this.initEditControl();
            }
            else if (status == '') //not loaded
                dnn.dom.loadScript(dnn.dom.getScriptPath() + script, '', this._performEditDelegate);
        }
    },

    initEditControl: function()
    {
        if (this.editWrapper.initialized)
        {
            this.editControl = this.editWrapper.control;
            this.editControl.className = this.container.className + ' ' + this.cssEdit;
            this.editWrapper.focus();
            if (this.editWrapper.loaded == false)
            {
                var eventObj = { keypress: this.handleKeyPress,
                    mousemove: this.mouseMove,
                    mouseout: this.mouseOut
                };

                if (this.onblurSave)
                    eventObj.blur = this.persistEdit;

                if (this.editWrapper.supportsCE || this.editWrapper.isRichText == false)	//if browser supports contentEditable or is a simple INPUT control
                    this.addHandlers(this.editControl, eventObj, this);
                else	//IFRAME event handlers
                    this.addHandlers(this.editContainer.contentWindow.document, eventObj, this);

                this.editWrapper.loaded = true;
            }
        }
    },

    persistEdit: function()
    {
        if (this.editWrapper.getText() != this.prevText)
        {
            if (this.invoke_compatHandler('beforeSave', null, this))
            {
                this.editControl.className = this.container.className + ' ' + this.cssWork;
                eval(this.callBack.replace('[TEXT]', dnn.escapeForEval(this.editWrapper.getText())));
            }
        }
        else
            this.showLabel();
    },

    cancelEdit: function()
    {
        this.editWrapper.setText(this.prevText);
        this.showLabel();
    },

    callBackStatus: function(result, ctx, req)
    {
        var lbl = ctx;
        lbl.invoke_compatHandler('callBackStatus', result, ctx, req);
    },

    callBackSuccess: function(result, ctx, req)
    {
        ctx.callBackStatus(result, ctx);
        ctx.invoke_handler('callBackSuccess', new dnn.controls.DNNCallbackEventArgs(result, ctx, req));
        ctx.showLabel();
	    ctx.flashLabel();
    },

    //obsolete
    raiseEvent: function(sFunc, evt, element)
    {
        if (this[sFunc].length > 0)
        {
            var ptr = eval(this[sFunc]);
            return ptr(evt, element) != false;
        }
        return true;
    },

    handleToolbarDisplay: function()
    {
        if (this.toolbar)
        {
            var inEdit = this.isEditMode();
            var btn;
            for (var key in this.toolbar.buttons)
            {
                btn = this.toolbar.buttons[key];
                if (typeof btn == 'function')	//safeguard against other js frameworks
                    continue;

	            if (key == 'edit') {
	            	btn.visible = !inEdit;
		            if (btn.visible) {
			            this.toolbar.css = this.toolbar.css.replace(" editMode", "");
		            } else {
			            this.toolbar.css = this.toolbar.css + " editMode";
		            }
	            } else if (this.isFormatButton(key))
		            btn.visible = (inEdit && this.editWrapper && this.editWrapper.isRichText);
	            else
		            btn.visible = inEdit;

            }
            this.toolbar.refresh();
        }
    },

    isFormatButton: function(key)
    {
        return '~bold~italic~underline~justifyleft~justifycenter~justifyright~insertorderedlist~insertunorderedlist~outdent~indent~createlink~'.indexOf('~' + key + '~') > -1;
    },

    showLabel: function()
    {
        this.container.innerHTML = this.editWrapper.getText();
        this.container.style.display = '';
        this.container.className = this.css;
        //this.editContainer.style.width = 0; //firefox workaround
        //this.editContainer.style.visibility = 'hidden';	//firefox workaround
        this.editContainer.style.display = 'none';
        this.handleToolbarDisplay();
    },

    flashLabel: function () {
    	var handler = this;
	    this.container.style.backgroundColor = "#fffacd";
	    setTimeout(function () {
		    handler.container.style.backgroundColor = "#fffff0";
		    setTimeout(function () {
			    handler.container.style.backgroundColor = "transparent";
            }, 300);
        }, 2500);
	},

    callBackFail: function(result, ctx, req)
    {
        ctx.invoke_handler('callBackFail', new dnn.controls.DNNCallbackEventArgs(result, ctx, req));
        ctx.cancelEdit();
    },

    handleKeyPress: function(e)
    {
        if (e.charCode == KEY_RETURN && this.editWrapper.supportsMultiLine == false)
        {
            if (this.saveOnEnter)
                this.persistEdit();
            e.preventDefault();
        }
        else if (e.charCode == KEY_ESCAPE)
        {
            this.cancelEdit();
            e.preventDefault();
        }
    },

    dispose: function()
    {
        this._toolbarActionDelegate = null;
        this._initToolbarDelegate = null;
        this._performEditDelegate = null;
        dnn.controls.DNNLabelEdit.callBaseMethod(this, 'dispose');
    }

}

dnn.controls.DNNLabelEdit.registerClass('dnn.controls.DNNLabelEdit', dnn.controls.control);<|endoftext|>


<commit_before>//TODO make RGB class
RGBObj = {}

//Now the Progrok class
Progrok = {}

Progrok.IS_WEBKIT = 'WebkitAppearance' in document.documentElement.style;

Progrok.RGB_STR_REGEX = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/;

Progrok.RGB_CHANGE_VELOCITY = 10; //increments of 10

Progrok.ANIMATE_INTERVAL_PERIOD_TIME = 10; //10ms

Progrok.INCR_COLORS = {};

//around 'palegreen'
Progrok.INCR_COLOR.GOOD_COLOR = {
  r: 150,
  g: 250,
  b: 150
};

//around 'gold'
Progrok.INCR_COLOR.WARN_COLOR = {
   r: 260,
   g: 220,
   b: 0
 };

//around 'tomato'
Progrok.INCR_COLOR.BAD_COLOR = {
    r: 220,
    g: 100,
    b: 70
  };

//map of (selector -> rule #) in bar_color_sheet
Progrok.BAR_SHEET_SELECTORS = {};
Progrok.BAR_SELECTORS_COUNT = 0;

Progrok.init = function (user_obj) {

  Progrok.BAR_STYLE = document.createElement('style');

  document.head.appendChild(Progrok.BAR_STYLE);

  Progrok.BAR_COLOR_SHEET = Progrok.BAR_STYLE.sheet;

  //TODO stuff with user_obj
};

Progrok.calcBarColor = function (perc, round_num, end_is_good) {
  //default arguments
  round_num typeof round_num === 'undefined' ? 1 : round_num;
  end_is_good = typeof end_is_good === 'undefined' ? true : end_is_good;
}
<commit_msg>Starting to do actual OOP/ProtoOP<commit_after>//TODO make RGB class
  //RGBObj = {};
  var RGB = function () {
    this.initFromComponents = 0;
    this.initFromObj = 1;
    this.initFromString = 2;
  }
//TODO

//Now the Progrok class
var Progrok = Progrok || {};

Progrok.IS_WEBKIT = 'WebkitAppearance' in document.documentElement.style;

Progrok.RGB_STR_REGEX = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/;

Progrok.RGB_CHANGE_VELOCITY = 10; //increments of 10

Progrok.ANIMATE_INTERVAL_PERIOD_TIME = 10; //10ms

Progrok.INCR_COLORS = {};

//around 'palegreen'
Progrok.INCR_COLOR.GOOD_COLOR = {
  r: 150,
  g: 250,
  b: 150
};

//around 'gold'
Progrok.INCR_COLOR.WARN_COLOR = {
   r: 260,
   g: 220,
   b: 0
 };

//around 'tomato'
Progrok.INCR_COLOR.BAD_COLOR = {
    r: 220,
    g: 100,
    b: 70
  };

//map of (selector -> rule #) in bar_color_sheet
Progrok.BAR_SHEET_SELECTORS = {};
Progrok.BAR_SELECTORS_COUNT = 0;

Progrok.init = function (user_obj) {

  Progrok.BAR_STYLE = document.createElement('style');

  document.head.appendChild(Progrok.BAR_STYLE);

  Progrok.BAR_COLOR_SHEET = Progrok.BAR_STYLE.sheet;

  //TODO stuff with user_obj
};

Progrok.calcBarColor = function (perc, round_num, end_is_good) {
  //default arguments
  round_num typeof round_num === 'undefined' ? 1 : round_num;
  end_is_good = typeof end_is_good === 'undefined' ? true : end_is_good;
}
<|endoftext|>


<commit_before>define([
	"dojo/_base/declare",
	"dojo/dom-class",
	"dojo/date",
	"dojo/date/locale",
	"./SpinWheel",
	"./SpinWheelSlot"
], function(declare, domClass, ddate, datelocale, SpinWheel, SpinWheelSlot){

/*=====
	var SpinWheel = dojox.mobile.SpinWheel;
	var SpinWheelSlot = dojox.mobile.SpinWheelSlot;
=====*/

	// module:
	//		dojox/mobile/SpinWheelDatePicker
	// summary:
	//		A SpinWheel-based date picker widget.

	//TODO: the api doc parser seems to fail if the 1st arg for declare (=class name) is missing..
	var SpinWheelYearSlot = declare(SpinWheelSlot, {
		buildRendering: function(){
			this.labels = [];
			if(this.labelFrom !== this.labelTo){
				var dtA = new Date(this.labelFrom, 0, 1);
				var i, idx;
				for(i = this.labelFrom, idx = 0; i <= this.labelTo; i++, idx++){
					dtA.setFullYear(i);
					this.labels.push(datelocale.format(dtA, {datePattern:"yyyy", selector:"date"}));
				}
			}
			this.inherited(arguments);
		}
	});

	var SpinWheelMonthSlot = declare(SpinWheelSlot, {
		buildRendering: function(){
			this.labels = [];
			var dtA = new Date(2000, 0, 1);
			var monthStr;
			for(var i = 0; i < 12; i++){
				dtA.setMonth(i);
				monthStr = datelocale.format(dtA, {datePattern:"MMM", selector:"date"});
				this.labels.push(monthStr);
			}
			this.inherited(arguments);
		}
	});

	var SpinWheelDaySlot = declare(SpinWheelSlot, {
	});

	return declare("dojox.mobile.SpinWheelDatePicker", SpinWheel, {
		// summary:
		//		A SpinWheel-based date picker widget.
		// description:
		//		SpinWheelDatePicker is a date picker widget. It is a subclass of
		//		dojox.mobile.SpinWheel. It has the year, month, and day slots.

		slotClasses: [
			SpinWheelYearSlot,
			SpinWheelMonthSlot,
			SpinWheelDaySlot
		],
		slotProps: [
			{labelFrom:1970, labelTo:2038},
			{},
			{labelFrom:1, labelTo:31}
		],

		buildRendering: function(){
			this.inherited(arguments);
			domClass.add(this.domNode, "mblSpinWheelDatePicker");
			this.connect(this.slots[1], "onFlickAnimationEnd", "onMonthSet");
			this.connect(this.slots[2], "onFlickAnimationEnd", "onDaySet");
		},

		reset: function(){
			// summary:
			//		Goes to today.
			var slots = this.slots;
			var now = new Date();
			var monthStr = datelocale.format(now, {datePattern:"MMM", selector:"date"});
			this.setValue([now.getFullYear(), monthStr, now.getDate()]);
		},

		onMonthSet: function(){
			// summary:
			//		A handler called when the month value is changed.
			var daysInMonth = this.onDaySet();
			var disableValuesTable = {28:[29,30,31], 29:[30,31], 30:[31], 31:[]};
			this.slots[2].disableValues(disableValuesTable[daysInMonth]);
		},

		onDaySet: function(){
			// summary:
			//		A handler called when the day value is changed.
			var y = this.slots[0].getValue();
			var m = this.slots[1].getValue();
			var newMonth = datelocale.parse(y+"/"+m, {datePattern:'yyyy/MMM', selector:'date'});
			var daysInMonth = ddate.getDaysInMonth(newMonth);
			var d = this.slots[2].getValue();
			if(daysInMonth < d){
				this.slots[2].setValue(daysInMonth);
			}
			return daysInMonth;
		}
	});
});
<commit_msg>Refs #13633 !strict Added fake comments for the api doc parser to work.<commit_after>define([
	"dojo/_base/declare",
	"dojo/dom-class",
	"dojo/date",
	"dojo/date/locale",
	"./SpinWheel",
	"./SpinWheelSlot"
], function(declare, domClass, ddate, datelocale, SpinWheel, SpinWheelSlot){

/*=====
	var SpinWheel = dojox.mobile.SpinWheel;
	var SpinWheelSlot = dojox.mobile.SpinWheelSlot;
=====*/

	// module:
	//		dojox/mobile/SpinWheelDatePicker
	// summary:
	//		A SpinWheel-based date picker widget.

	//TODO: the api doc parser seems to fail if the 1st arg for declare (=class name) is missing..
	var SpinWheelYearSlot = declare(/*===== "dojox.mobile.SpinWheelYearSlot", =====*/ SpinWheelSlot, {
		buildRendering: function(){
			this.labels = [];
			if(this.labelFrom !== this.labelTo){
				var dtA = new Date(this.labelFrom, 0, 1);
				var i, idx;
				for(i = this.labelFrom, idx = 0; i <= this.labelTo; i++, idx++){
					dtA.setFullYear(i);
					this.labels.push(datelocale.format(dtA, {datePattern:"yyyy", selector:"date"}));
				}
			}
			this.inherited(arguments);
		}
	});

	var SpinWheelMonthSlot = declare(/*===== "dojox.mobile.SpinWheelMonthSlot", =====*/ SpinWheelSlot, {
		buildRendering: function(){
			this.labels = [];
			var dtA = new Date(2000, 0, 1);
			var monthStr;
			for(var i = 0; i < 12; i++){
				dtA.setMonth(i);
				monthStr = datelocale.format(dtA, {datePattern:"MMM", selector:"date"});
				this.labels.push(monthStr);
			}
			this.inherited(arguments);
		}
	});

	var SpinWheelDaySlot = declare(/*===== "dojox.mobile.SpinWheelDaySlot", =====*/ SpinWheelSlot, {
	});

	return declare("dojox.mobile.SpinWheelDatePicker", SpinWheel, {
		// summary:
		//		A SpinWheel-based date picker widget.
		// description:
		//		SpinWheelDatePicker is a date picker widget. It is a subclass of
		//		dojox.mobile.SpinWheel. It has the year, month, and day slots.

		slotClasses: [
			SpinWheelYearSlot,
			SpinWheelMonthSlot,
			SpinWheelDaySlot
		],
		slotProps: [
			{labelFrom:1970, labelTo:2038},
			{},
			{labelFrom:1, labelTo:31}
		],

		buildRendering: function(){
			this.inherited(arguments);
			domClass.add(this.domNode, "mblSpinWheelDatePicker");
			this.connect(this.slots[1], "onFlickAnimationEnd", "onMonthSet");
			this.connect(this.slots[2], "onFlickAnimationEnd", "onDaySet");
		},

		reset: function(){
			// summary:
			//		Goes to today.
			var slots = this.slots;
			var now = new Date();
			var monthStr = datelocale.format(now, {datePattern:"MMM", selector:"date"});
			this.setValue([now.getFullYear(), monthStr, now.getDate()]);
		},

		onMonthSet: function(){
			// summary:
			//		A handler called when the month value is changed.
			var daysInMonth = this.onDaySet();
			var disableValuesTable = {28:[29,30,31], 29:[30,31], 30:[31], 31:[]};
			this.slots[2].disableValues(disableValuesTable[daysInMonth]);
		},

		onDaySet: function(){
			// summary:
			//		A handler called when the day value is changed.
			var y = this.slots[0].getValue();
			var m = this.slots[1].getValue();
			var newMonth = datelocale.parse(y+"/"+m, {datePattern:'yyyy/MMM', selector:'date'});
			var daysInMonth = ddate.getDaysInMonth(newMonth);
			var d = this.slots[2].getValue();
			if(daysInMonth < d){
				this.slots[2].setValue(daysInMonth);
			}
			return daysInMonth;
		}
	});
});
<|endoftext|>


<commit_before>// Opening for events
const eventTitle = getElementByClassName('event-title', 0)
const eventSubtitle = getElementByClassName('event-subtitle', 0)
const eventDetails = getElementByClassName('event-details', 0)
// Fade in first slide
eventTitle.classList.add('fade-move')
eventSubtitle.classList.add('fade-move')
eventDetails.classList.add('fade-move')
// Email signup form
setTimeout(() => changeEmailContainerBackground(getElementByClassName('email-container-background', 0)), 600)

// Event listener for if reg form is closed
const regFormModalStatus = getElementByClassName('modal-status registration', 0)
const regFormModal = getElementByClassName('modal registration', 0)
const regFormModalWindow = getElementByClassName('modal-window registration', 0)
const regFormContainer = getElementByClassName('container reg-form', 0)
const regFormButtons = getElementsByClassName('button register')
for (let i = 0; i < regFormButtons.length; i++) {
	onClick(regFormButtons[i], () => {
		// Prepare for fade in
		regFormModal.style.opacity = '0'
		// Unhide modal
		showElement(regFormModalStatus)
		// Fade in modal window
		setTimeout(() => {
			// Fade in
			regFormModal.style.opacity = '1.0'
			// Scroll to top
			regFormContainer.scrollTop = 0
			// Show reg form: browser error that doesn’t show opacity of elements inside modal window unless body is scrolled by at least 1 px
			window.scrollBy(0, 1)
			// Prevent background from scrolling
			document.body.style.overflow = 'hidden'
		}, 100)

	})
}

const regFormClose = getElementByClassName('reg-form-close', 0)
onClick(regFormClose, () => {
	document.body.style.overflow = 'visible'
	regFormModal.style.opacity = '0'
	setTimeout(() => hideElement(regFormModalStatus), 200)
})

// Event summary “Read more...” expansion
getElementByClassName('text read-more', 0).addEventListener('mouseover', () => {
	hideElement(getElementByClassName('text read-more'))
	hideElement(getElementByClassName('text summary'))
	getElementByClassName('text description').classList.add('display')
	setTimeout(() => getElementByClassName('text description display').classList.add('fade'), 100)
})

// Prevent accidental submission of form through 'enter' key
onKeyPress(document, e => {
	if (isInput(e.target) && e.which === 13) {
		e.preventDefault()
		return false
	}
})

let countries = [{value:'AF',label:'Afghanistan'},{value:'AX',label:'Åland Islands'},{value:'AL',label:'Albania'},{value:'DZ',label:'Algeria'},{value:'AS',label:'American Samoa'},{value:'AD',label:'Andorra'},{value:'AO',label:'Angola'},{value:'AI',label:'Anguilla'},{value:'AQ',label:'Antarctica'},{value:'AG',label:'Antigua and Barbuda'},{value:'AR',label:'Argentina'},{value:'AM',label:'Armenia'},{value:'AW',label:'Aruba'},{value:'AU',label:'Australia'},{value:'AT',label:'Austria'},{value:'AZ',label:'Azerbaijan'},{value:'BS',label:'Bahamas'},{value:'BH',label:'Bahrain'},{value:'BD',label:'Bangladesh'},{value:'BB',label:'Barbados'},{value:'BY',label:'Belarus'},{value:'BE',label:'Belgium'},{value:'BZ',label:'Belize'},{value:'BJ',label:'Benin'},{value:'BM',label:'Bermuda'},{value:'BT',label:'Bhutan'},{value:'BO',label:'Bolivia'},{value:'BA',label:'Bosnia and Herzegovina'},{value:'BW',label:'Botswana'},{value:'BV',label:'Bouvet Island'},{value:'BR',label:'Brazil'},{value:'IO',label:'British Indian Ocean Territory'},{value:'BN',label:'Brunei Darussalam'},{value:'BG',label:'Bulgaria'},{value:'BF',label:'Burkina Faso'},{value:'BI',label:'Burundi'},{value:'KH',label:'Cambodia'},{value:'CM',label:'Cameroon'},{value:'CA',label:'Canada'},{value:'CV',label:'Cape Verde'},{value:'KY',label:'Cayman Islands'},{value:'CF',label:'Central African Republic'},{value:'TD',label:'Chad'},{value:'CL',label:'Chile'},{value:'CN',label:'China, People’s Republic of'},{value:'CX',label:'Christmas Island'},{value:'CC',label:'Cocos (Keeling) Islands'},{value:'CO',label:'Colombia'},{value:'KM',label:'Comoros'},{value:'CG',label:'Congo'},{value:'CD',label:'Congo, The Democratic Republic of the'},{value:'CK',label:'Cook Islands'},{value:'CR',label:'Costa Rica'},{value:'CI',label:'Cote D’Ivoire'},{value:'HR',label:'Croatia'},{value:'CU',label:'Cuba'},{value:'CY',label:'Cyprus'},{value:'CZ',label:'Czech Republic'},{value:'DK',label:'Denmark'},{value:'DJ',label:'Djibouti'},{value:'DM',label:'Dominica'},{value:'DO',label:'Dominican Republic'},{value:'EC',label:'Ecuador'},{value:'EG',label:'Egypt'},{value:'SV',label:'El Salvador'},{value:'GQ',label:'Equatorial Guinea'},{value:'ER',label:'Eritrea'},{value:'EE',label:'Estonia'},{value:'ET',label:'Ethiopia'},{value:'FK',label:'Falkland Islands (Malvinas)'},{value:'FO',label:'Faroe Islands'},{value:'FJ',label:'Fiji'},{value:'FI',label:'Finland'},{value:'FR',label:'France'},{value:'GF',label:'French Guiana'},{value:'PF',label:'French Polynesia'},{value:'TF',label:'French Southern Territories'},{value:'GA',label:'Gabon'},{value:'GM',label:'Gambia'},{value:'GE',label:'Georgia'},{value:'DE',label:'Germany'},{value:'GH',label:'Ghana'},{value:'GI',label:'Gibraltar'},{value:'GR',label:'Greece'},{value:'GL',label:'Greenland'},{value:'GD',label:'Grenada'},{value:'GP',label:'Guadeloupe'},{value:'GU',label:'Guam'},{value:'GT',label:'Guatemala'},{value:'GG',label:'Guernsey'},{value:'GN',label:'Guinea'},{value:'GW',label:'Guinea-Bissau'},{value:'GY',label:'Guyana'},{value:'HT',label:'Haiti'},{value:'HM',label:'Heard Island and Mcdonald Islands'},{value:'VA',label:'Holy See (Vatican City State)'},{value:'HN',label:'Honduras'},{value:'HK',label:'Hong Kong'},{value:'HU',label:'Hungary'},{value:'IS',label:'Iceland'},{value:'IN',label:'India'},{value:'ID',label:'Indonesia'},{value:'IR',label:'Iran, Islamic Republic Of'},{value:'IQ',label:'Iraq'},{value:'IE',label:'Ireland'},{value:'IM',label:'Isle of Man'},{value:'IL',label:'Israel'},{value:'IT',label:'Italy'},{value:'JM',label:'Jamaica'},{value:'JP',label:'Japan'},{value:'JE',label:'Jersey'},{value:'JO',label:'Jordan'},{value:'KZ',label:'Kazakhstan'},{value:'KE',label:'Kenya'},{value:'KI',label:'Kiribati'},{value:'KP',label:'Democratic People’s Republic of Korea'},{value:'KR',label:'Korea, Republic of'},{value:'XK',label:'Kosovo'},{value:'KW',label:'Kuwait'},{value:'KG',label:'Kyrgyzstan'},{value:'LA',label:'Lao People’s Democratic Republic'},{value:'LV',label:'Latvia'},{value:'LB',label:'Lebanon'},{value:'LS',label:'Lesotho'},{value:'LR',label:'Liberia'},{value:'LY',label:'Libyan Arab Jamahiriya'},{value:'LI',label:'Liechtenstein'},{value:'LT',label:'Lithuania'},{value:'LU',label:'Luxembourg'},{value:'MO',label:'Macao'},{value:'MK',label:'Macedonia, The Former Yugoslav Republic of'},{value:'MG',label:'Madagascar'},{value:'MW',label:'Malawi'},{value:'MY',label:'Malaysia'},{value:'MV',label:'Maldives'},{value:'ML',label:'Mali'},{value:'MT',label:'Malta'},{value:'MH',label:'Marshall Islands'},{value:'MQ',label:'Martinique'},{value:'MR',label:'Mauritania'},{value:'MU',label:'Mauritius'},{value:'YT',label:'Mayotte'},{value:'MX',label:'Mexico'},{value:'FM',label:'Micronesia, Federated States of'},{value:'MD',label:'Moldova, Republic of'},{value:'MC',label:'Monaco'},{value:'MN',label:'Mongolia'},{value:'ME',label:'Montenegro'},{value:'MS',label:'Montserrat'},{value:'MA',label:'Morocco'},{value:'MZ',label:'Mozambique'},{value:'MM',label:'Myanmar'},{value:'NA',label:'Namibia'},{value:'NR',label:'Nauru'},{value:'NP',label:'Nepal'},{value:'NL',label:'Netherlands'},{value:'AN',label:'Netherlands Antilles'},{value:'NC',label:'New Caledonia'},{value:'NZ',label:'New Zealand'},{value:'NI',label:'Nicaragua'},{value:'NE',label:'Niger'},{value:'NG',label:'Nigeria'},{value:'NU',label:'Niue'},{value:'NF',label:'Norfolk Island'},{value:'MP',label:'Northern Mariana Islands'},{value:'NO',label:'Norway'},{value:'OM',label:'Oman'},{value:'PK',label:'Pakistan'},{value:'PW',label:'Palau'},{value:'PS',label:'Palestine, State of'},{value:'PA',label:'Panama'},{value:'PG',label:'Papua New Guinea'},{value:'PY',label:'Paraguay'},{value:'PE',label:'Peru'},{value:'PH',label:'Philippines'},{value:'PN',label:'Pitcairn'},{value:'PL',label:'Poland'},{value:'PT',label:'Portugal'},{value:'PR',label:'Puerto Rico'},{value:'QA',label:'Qatar'},{value:'RE',label:'Reunion'},{value:'RO',label:'Romania'},{value:'RU',label:'Russian Federation'},{value:'RW',label:'Rwanda'},{value:'SH',label:'Saint Helena'},{value:'KN',label:'Saint Kitts and Nevis'},{value:'LC',label:'Saint Lucia'},{value:'PM',label:'Saint Pierre and Miquelon'},{value:'VC',label:'Saint Vincent and the Grenadines'},{value:'WS',label:'Samoa'},{value:'SM',label:'San Marino'},{value:'ST',label:'Sao Tome and Principe'},{value:'SA',label:'Saudi Arabia'},{value:'SN',label:'Senegal'},{value:'RS',label:'Serbia'},{value:'SC',label:'Seychelles'},{value:'SL',label:'Sierra Leone'},{value:'SG',label:'Singapore'},{value:'SK',label:'Slovakia'},{value:'SI',label:'Slovenia'},{value:'SB',label:'Solomon Islands'},{value:'SO',label:'Somalia'},{value:'ZA',label:'South Africa'},{value:'GS',label:'South Georgia and the South Sandwich Islands'},{value:'ES',label:'Spain'},{value:'LK',label:'Sri Lanka'},{value:'SD',label:'Sudan'},{value:'SR',label:'Suriname'},{value:'SJ',label:'Svalbard and Jan Mayen'},{value:'SZ',label:'Swaziland'},{value:'SE',label:'Sweden'},{value:'CH',label:'Switzerland'},{value:'SY',label:'Syrian Arab Republic'},{value:'TW',label:'Taiwan, Republic of China'},{value:'TJ',label:'Tajikistan'},{value:'TZ',label:'Tanzania, United Republic of'},{value:'TH',label:'Thailand'},{value:'TL',label:'Timor-Leste'},{value:'TG',label:'Togo'},{value:'TK',label:'Tokelau'},{value:'TO',label:'Tonga'},{value:'TT',label:'Trinidad and Tobago'},{value:'TN',label:'Tunisia'},{value:'TR',label:'Turkey'},{value:'TM',label:'Turkmenistan'},{value:'TC',label:'Turks and Caicos Islands'},{value:'TV',label:'Tuvalu'},{value:'UG',label:'Uganda'},{value:'UA',label:'Ukraine'},{value:'AE',label:'United Arab Emirates'},{value:'GB',label:'United Kingdom'},{value:'US',label:'United States'},{value:'UM',label:'United States Minor Outlying Islands'},{value:'UY',label:'Uruguay'},{value:'UZ',label:'Uzbekistan'},{value:'VU',label:'Vanuatu'},{value:'VE',label:'Venezuela'},{value:'VN',label:'Viet Nam'},{value:'VG',label:'Virgin Islands, British'},{value:'VI',label:'Virgin Islands, U.S.'},{value:'WF',label:'Wallis and Futuna'},{value:'EH',label:'Western Sahara'},{value:'YE',label:'Yemen'},{value:'ZM',label:'Zambia'},{value:'ZW',label:'Zimbabwe'}]

// Countries
if (getElementById('country')) {
	for(let i in countries) {
		let option = document.createElement('option')
		option.text = countries[i].label
		option.value = countries[i].value
		option.selected = countries[i] === 'United States'
			? true
			: false
		appendSelect(getElementById('country'), option)
	}
}

// Load reg form scripts
const baseScriptUrl = 'https://ecstaticliving.github.io/ecstaticliving.com/dev/events/'
const scripts = ['elements', 'functions', 'onchange', 'webflow', 'payment']
// Load scripts synchronously, one after another, to make sure hierarchy is respected.
const loadScript = index => {
	let js = document.createElement('script')
	js.src = baseScriptUrl + scripts[index] + '.js'
	js.onload = () => {
		// Once final script has loaded, initialise
		if (scripts[index] === 'payment' && (page() === 'Event' || page() === 'Update')) {
			resetForm()
			scriptsHaveBeenLoaded = true
		}
		else {
			loadScript(index + 1)
		}
	}
	document.head.appendChild(js)
}
loadScript(0)
<commit_msg>Reg form modal display.<commit_after>// Opening for events
const eventTitle = getElementByClassName('event-title', 0)
const eventSubtitle = getElementByClassName('event-subtitle', 0)
const eventDetails = getElementByClassName('event-details', 0)
// Fade in first slide
eventTitle.classList.add('fade-move')
eventSubtitle.classList.add('fade-move')
eventDetails.classList.add('fade-move')
// Email signup form
setTimeout(() => changeEmailContainerBackground(getElementByClassName('email-container-background', 0)), 600)

// Event listener for if reg form is closed
const regFormModalStatus = getElementByClassName('modal-status registration', 0)
const regFormModal = getElementByClassName('modal registration', 0)
const regFormModalWindow = getElementByClassName('modal-window registration', 0)
const regFormContainer = getElementByClassName('container reg-form', 0)
const regFormButtons = getElementsByClassName('button register')
for (let i = 0; i < regFormButtons.length; i++) {
	onClick(regFormButtons[i], () => {
		// Prepare for fade in
		// regFormModal.style.opacity = '0'
		// Unhide modal
		showElement(regFormModalStatus)
		// Fade in modal window
		setTimeout(() => {
			// Fade in
			// regFormModal.style.opacity = '1.0'
			// Scroll to top
			regFormContainer.scrollTop = 0
			// Show reg form: browser error that doesn’t show opacity of elements inside modal window unless body is scrolled by at least 1 px
			window.scrollBy(0, 1)
			// Prevent background from scrolling
			document.body.style.overflow = 'hidden'
		}, 100)

	})
}

const regFormClose = getElementByClassName('reg-form-close', 0)
onClick(regFormClose, () => {
	document.body.style.overflow = 'visible'
	regFormModal.style.opacity = '0'
	setTimeout(() => hideElement(regFormModalStatus), 200)
})

// Event summary “Read more...” expansion
getElementByClassName('text read-more', 0).addEventListener('mouseover', () => {
	hideElement(getElementByClassName('text read-more'))
	hideElement(getElementByClassName('text summary'))
	getElementByClassName('text description').classList.add('display')
	setTimeout(() => getElementByClassName('text description display').classList.add('fade'), 100)
})

// Prevent accidental submission of form through 'enter' key
onKeyPress(document, e => {
	if (isInput(e.target) && e.which === 13) {
		e.preventDefault()
		return false
	}
})

let countries = [{value:'AF',label:'Afghanistan'},{value:'AX',label:'Åland Islands'},{value:'AL',label:'Albania'},{value:'DZ',label:'Algeria'},{value:'AS',label:'American Samoa'},{value:'AD',label:'Andorra'},{value:'AO',label:'Angola'},{value:'AI',label:'Anguilla'},{value:'AQ',label:'Antarctica'},{value:'AG',label:'Antigua and Barbuda'},{value:'AR',label:'Argentina'},{value:'AM',label:'Armenia'},{value:'AW',label:'Aruba'},{value:'AU',label:'Australia'},{value:'AT',label:'Austria'},{value:'AZ',label:'Azerbaijan'},{value:'BS',label:'Bahamas'},{value:'BH',label:'Bahrain'},{value:'BD',label:'Bangladesh'},{value:'BB',label:'Barbados'},{value:'BY',label:'Belarus'},{value:'BE',label:'Belgium'},{value:'BZ',label:'Belize'},{value:'BJ',label:'Benin'},{value:'BM',label:'Bermuda'},{value:'BT',label:'Bhutan'},{value:'BO',label:'Bolivia'},{value:'BA',label:'Bosnia and Herzegovina'},{value:'BW',label:'Botswana'},{value:'BV',label:'Bouvet Island'},{value:'BR',label:'Brazil'},{value:'IO',label:'British Indian Ocean Territory'},{value:'BN',label:'Brunei Darussalam'},{value:'BG',label:'Bulgaria'},{value:'BF',label:'Burkina Faso'},{value:'BI',label:'Burundi'},{value:'KH',label:'Cambodia'},{value:'CM',label:'Cameroon'},{value:'CA',label:'Canada'},{value:'CV',label:'Cape Verde'},{value:'KY',label:'Cayman Islands'},{value:'CF',label:'Central African Republic'},{value:'TD',label:'Chad'},{value:'CL',label:'Chile'},{value:'CN',label:'China, People’s Republic of'},{value:'CX',label:'Christmas Island'},{value:'CC',label:'Cocos (Keeling) Islands'},{value:'CO',label:'Colombia'},{value:'KM',label:'Comoros'},{value:'CG',label:'Congo'},{value:'CD',label:'Congo, The Democratic Republic of the'},{value:'CK',label:'Cook Islands'},{value:'CR',label:'Costa Rica'},{value:'CI',label:'Cote D’Ivoire'},{value:'HR',label:'Croatia'},{value:'CU',label:'Cuba'},{value:'CY',label:'Cyprus'},{value:'CZ',label:'Czech Republic'},{value:'DK',label:'Denmark'},{value:'DJ',label:'Djibouti'},{value:'DM',label:'Dominica'},{value:'DO',label:'Dominican Republic'},{value:'EC',label:'Ecuador'},{value:'EG',label:'Egypt'},{value:'SV',label:'El Salvador'},{value:'GQ',label:'Equatorial Guinea'},{value:'ER',label:'Eritrea'},{value:'EE',label:'Estonia'},{value:'ET',label:'Ethiopia'},{value:'FK',label:'Falkland Islands (Malvinas)'},{value:'FO',label:'Faroe Islands'},{value:'FJ',label:'Fiji'},{value:'FI',label:'Finland'},{value:'FR',label:'France'},{value:'GF',label:'French Guiana'},{value:'PF',label:'French Polynesia'},{value:'TF',label:'French Southern Territories'},{value:'GA',label:'Gabon'},{value:'GM',label:'Gambia'},{value:'GE',label:'Georgia'},{value:'DE',label:'Germany'},{value:'GH',label:'Ghana'},{value:'GI',label:'Gibraltar'},{value:'GR',label:'Greece'},{value:'GL',label:'Greenland'},{value:'GD',label:'Grenada'},{value:'GP',label:'Guadeloupe'},{value:'GU',label:'Guam'},{value:'GT',label:'Guatemala'},{value:'GG',label:'Guernsey'},{value:'GN',label:'Guinea'},{value:'GW',label:'Guinea-Bissau'},{value:'GY',label:'Guyana'},{value:'HT',label:'Haiti'},{value:'HM',label:'Heard Island and Mcdonald Islands'},{value:'VA',label:'Holy See (Vatican City State)'},{value:'HN',label:'Honduras'},{value:'HK',label:'Hong Kong'},{value:'HU',label:'Hungary'},{value:'IS',label:'Iceland'},{value:'IN',label:'India'},{value:'ID',label:'Indonesia'},{value:'IR',label:'Iran, Islamic Republic Of'},{value:'IQ',label:'Iraq'},{value:'IE',label:'Ireland'},{value:'IM',label:'Isle of Man'},{value:'IL',label:'Israel'},{value:'IT',label:'Italy'},{value:'JM',label:'Jamaica'},{value:'JP',label:'Japan'},{value:'JE',label:'Jersey'},{value:'JO',label:'Jordan'},{value:'KZ',label:'Kazakhstan'},{value:'KE',label:'Kenya'},{value:'KI',label:'Kiribati'},{value:'KP',label:'Democratic People’s Republic of Korea'},{value:'KR',label:'Korea, Republic of'},{value:'XK',label:'Kosovo'},{value:'KW',label:'Kuwait'},{value:'KG',label:'Kyrgyzstan'},{value:'LA',label:'Lao People’s Democratic Republic'},{value:'LV',label:'Latvia'},{value:'LB',label:'Lebanon'},{value:'LS',label:'Lesotho'},{value:'LR',label:'Liberia'},{value:'LY',label:'Libyan Arab Jamahiriya'},{value:'LI',label:'Liechtenstein'},{value:'LT',label:'Lithuania'},{value:'LU',label:'Luxembourg'},{value:'MO',label:'Macao'},{value:'MK',label:'Macedonia, The Former Yugoslav Republic of'},{value:'MG',label:'Madagascar'},{value:'MW',label:'Malawi'},{value:'MY',label:'Malaysia'},{value:'MV',label:'Maldives'},{value:'ML',label:'Mali'},{value:'MT',label:'Malta'},{value:'MH',label:'Marshall Islands'},{value:'MQ',label:'Martinique'},{value:'MR',label:'Mauritania'},{value:'MU',label:'Mauritius'},{value:'YT',label:'Mayotte'},{value:'MX',label:'Mexico'},{value:'FM',label:'Micronesia, Federated States of'},{value:'MD',label:'Moldova, Republic of'},{value:'MC',label:'Monaco'},{value:'MN',label:'Mongolia'},{value:'ME',label:'Montenegro'},{value:'MS',label:'Montserrat'},{value:'MA',label:'Morocco'},{value:'MZ',label:'Mozambique'},{value:'MM',label:'Myanmar'},{value:'NA',label:'Namibia'},{value:'NR',label:'Nauru'},{value:'NP',label:'Nepal'},{value:'NL',label:'Netherlands'},{value:'AN',label:'Netherlands Antilles'},{value:'NC',label:'New Caledonia'},{value:'NZ',label:'New Zealand'},{value:'NI',label:'Nicaragua'},{value:'NE',label:'Niger'},{value:'NG',label:'Nigeria'},{value:'NU',label:'Niue'},{value:'NF',label:'Norfolk Island'},{value:'MP',label:'Northern Mariana Islands'},{value:'NO',label:'Norway'},{value:'OM',label:'Oman'},{value:'PK',label:'Pakistan'},{value:'PW',label:'Palau'},{value:'PS',label:'Palestine, State of'},{value:'PA',label:'Panama'},{value:'PG',label:'Papua New Guinea'},{value:'PY',label:'Paraguay'},{value:'PE',label:'Peru'},{value:'PH',label:'Philippines'},{value:'PN',label:'Pitcairn'},{value:'PL',label:'Poland'},{value:'PT',label:'Portugal'},{value:'PR',label:'Puerto Rico'},{value:'QA',label:'Qatar'},{value:'RE',label:'Reunion'},{value:'RO',label:'Romania'},{value:'RU',label:'Russian Federation'},{value:'RW',label:'Rwanda'},{value:'SH',label:'Saint Helena'},{value:'KN',label:'Saint Kitts and Nevis'},{value:'LC',label:'Saint Lucia'},{value:'PM',label:'Saint Pierre and Miquelon'},{value:'VC',label:'Saint Vincent and the Grenadines'},{value:'WS',label:'Samoa'},{value:'SM',label:'San Marino'},{value:'ST',label:'Sao Tome and Principe'},{value:'SA',label:'Saudi Arabia'},{value:'SN',label:'Senegal'},{value:'RS',label:'Serbia'},{value:'SC',label:'Seychelles'},{value:'SL',label:'Sierra Leone'},{value:'SG',label:'Singapore'},{value:'SK',label:'Slovakia'},{value:'SI',label:'Slovenia'},{value:'SB',label:'Solomon Islands'},{value:'SO',label:'Somalia'},{value:'ZA',label:'South Africa'},{value:'GS',label:'South Georgia and the South Sandwich Islands'},{value:'ES',label:'Spain'},{value:'LK',label:'Sri Lanka'},{value:'SD',label:'Sudan'},{value:'SR',label:'Suriname'},{value:'SJ',label:'Svalbard and Jan Mayen'},{value:'SZ',label:'Swaziland'},{value:'SE',label:'Sweden'},{value:'CH',label:'Switzerland'},{value:'SY',label:'Syrian Arab Republic'},{value:'TW',label:'Taiwan, Republic of China'},{value:'TJ',label:'Tajikistan'},{value:'TZ',label:'Tanzania, United Republic of'},{value:'TH',label:'Thailand'},{value:'TL',label:'Timor-Leste'},{value:'TG',label:'Togo'},{value:'TK',label:'Tokelau'},{value:'TO',label:'Tonga'},{value:'TT',label:'Trinidad and Tobago'},{value:'TN',label:'Tunisia'},{value:'TR',label:'Turkey'},{value:'TM',label:'Turkmenistan'},{value:'TC',label:'Turks and Caicos Islands'},{value:'TV',label:'Tuvalu'},{value:'UG',label:'Uganda'},{value:'UA',label:'Ukraine'},{value:'AE',label:'United Arab Emirates'},{value:'GB',label:'United Kingdom'},{value:'US',label:'United States'},{value:'UM',label:'United States Minor Outlying Islands'},{value:'UY',label:'Uruguay'},{value:'UZ',label:'Uzbekistan'},{value:'VU',label:'Vanuatu'},{value:'VE',label:'Venezuela'},{value:'VN',label:'Viet Nam'},{value:'VG',label:'Virgin Islands, British'},{value:'VI',label:'Virgin Islands, U.S.'},{value:'WF',label:'Wallis and Futuna'},{value:'EH',label:'Western Sahara'},{value:'YE',label:'Yemen'},{value:'ZM',label:'Zambia'},{value:'ZW',label:'Zimbabwe'}]

// Countries
if (getElementById('country')) {
	for(let i in countries) {
		let option = document.createElement('option')
		option.text = countries[i].label
		option.value = countries[i].value
		option.selected = countries[i] === 'United States'
			? true
			: false
		appendSelect(getElementById('country'), option)
	}
}

// Load reg form scripts
const baseScriptUrl = 'https://ecstaticliving.github.io/ecstaticliving.com/dev/events/'
const scripts = ['elements', 'functions', 'onchange', 'webflow', 'payment']
// Load scripts synchronously, one after another, to make sure hierarchy is respected.
const loadScript = index => {
	let js = document.createElement('script')
	js.src = baseScriptUrl + scripts[index] + '.js'
	js.onload = () => {
		// Once final script has loaded, initialise
		if (scripts[index] === 'payment' && (page() === 'Event' || page() === 'Update')) {
			resetForm()
			scriptsHaveBeenLoaded = true
		}
		else {
			loadScript(index + 1)
		}
	}
	document.head.appendChild(js)
}
loadScript(0)
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you 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.
 *
 */
var user = {};
(function (server, user) {

    var USER_REGISTRY = 'server.user.registry';

    var USER_SPACE = 'server.user.space';

    var USER_ROLE_PREFIX = 'Internal/private_';

    var cleanUsername = function (username) {
        /**
         * this is a one-way hash function, @ is replaced if the user name is an email
         * if the user name is coming from a secondery user store it will be second.com/user hence
         * "/" will be replaced.
         */

        return username.replace('@', ':').replace('/', ':');
    };

    user.cleanUsername=function(username){
        return cleanUsername(username);
    };

    user.privateRole = function (username) {
        return USER_ROLE_PREFIX + cleanUsername(username);
    };

    user.USER_OPTIONS = 'server.user.options';

    /**
     * Initializes the user environment for the specified tenant. If it is already initialized, then will be skipped.
     */
    user.init = function (options) {
        var event = require('event');
        event.on('tenantCreate', function (tenantId) {

        });

        event.on('tenantLoad', function (tenantId) {
            var registry = server.systemRegistry(tenantId);
            user.configs(tenantId, JSON.parse(registry.content(options.tenantConfigs)));
        });

        event.on('tenantUnload', function (tenantId) {

        });

        event.on('login', function (tenantId, usr, session) {
            var space,
                carbon = require('carbon');
            server.current(session, usr);
            session.put(USER_REGISTRY, new carbon.registry.Registry(server.instance(), {
                username: usr.username,
                tenantId: tenantId
            }));
            space = user.userSpace(usr);
            session.put(USER_SPACE, space);
            if (!usr.isAuthorized(space, carbon.registry.actions.PUT)) {
                event.emit('userRegister', tenantId, usr);
            }
        });

        event.on('logout', function (tenantId, usr, session) {
            server.current(session, null);
            session.remove(USER_SPACE);
            session.remove(USER_REGISTRY);
        });

        event.on('userRegister', function (tenantId, usr) {
            var role, perms, r, p,
                log = new Log(),
                carbon = require('carbon'),
                event = require('event'),
                um = server.userManager(usr.tenantId),
                opts = user.configs(usr.tenantId),
                space = user.userSpace(usr),
                registry = server.systemRegistry(tenantId);
            if (!registry.exists(space)) {
                registry.put(space, {
                    collection: true
                });
                if (log.isDebugEnabled()) {
                    log.debug('user space was created for user : ' + usr.username + ' at ' + space);
                }
            }
            role = user.privateRole(usr.username);
            perms = {};
            perms[space] = [
                carbon.registry.actions.GET,
                carbon.registry.actions.PUT,
                carbon.registry.actions.DELETE,
                carbon.registry.actions.AUTHORIZE
            ];
            p = opts.permissions.login;
            for (r in p) {
                if (p.hasOwnProperty(r)) {
                    perms[r] = p[r];
                }
            }
            if (!um.roleExists(role)) {
                um.addRole(role, [], perms);
            }
            if (!usr.hasRoles([role])) {
                usr.addRoles([role]);
            }
            um.authorizeRole(user.privateRole(usr.username), perms);
            if (log.isDebugEnabled()) {
                log.debug('user ' + usr.username + ' was initialized and role ' + role +
                    ' was authorized to access user space ' + space);
            }
        });
    };

    /**
     * Returns user options of the tenant.
     * @return {Object}
     */
    user.configs = function (tenantId, configs) {
        var o = server.configs(tenantId);
        return configs ? (o[user.USER_OPTIONS] = configs) : o[user.USER_OPTIONS];
    };

    /**
     * Logs in a user to the store. Username might contains the domain part in case of MT mode.
     * @param username ruchira or ruchira@ruchira.com
     * @param password
     * @param session
     * @return {boolean}
     */
    user.login = function (username, password, session) {
        var carbon = require('carbon'),
            event = require('event'),
            serv = server.instance();
        if (!serv.authenticate(username, password)) {
            return false;
        }
        return user.permitted(username, session);
    };

    user.permitted = function (username, session) {
        //load the tenant if it hasn't been loaded yet.
        var opts, um, perms, perm, actions, length, i,
            authorized = false,
            carbon = require('carbon'),
            event = require('event'),
            usr = carbon.server.tenantUser(username);
        if (!user.configs(usr.tenantId)) {
            event.emit('tenantLoad', usr.tenantId);
        }

        opts = user.configs(usr.tenantId);
        um = server.userManager(usr.tenantId);
        usr = um.getUser(usr.username);
        usr.tenantDomain = carbon.server.tenantDomain({tenantId: usr.tenantId});
        perms = opts.permissions.login;
        L1:
            for (perm in perms) {
                if (perms.hasOwnProperty(perm)) {
                    actions = perms[perm];
                    var log = new Log();
                    length = actions.length;
                    for (i = 0; i < length; i++) {
                        if (usr.isAuthorized(perm, actions[i])) {
                            authorized = true;
                            break L1;
                        }
                    }
                }
            }
        if (!authorized) {
            return false;
        }
        event.emit('login', usr.tenantId, usr, session);
        return true;
    };

    /**
     * Checks whether the logged in user has permission to the specified action.
     * @param user
     * @param permission
     * @param action
     * @return {*}
     */
    user.isAuthorized = function (user, permission, action) {
        var um = server.userManager(user.tenantId);
        return um.getUser(user.username).isAuthorized(permission, action);
    };

    /**
     * Returns the user's registry space. This should be called once with the username,
     * then can be called without the username.
     * @param usr user object
     * @return {*}
     */
    user.userSpace = function (usr) {
        try {
            return user.configs(usr.tenantId).userSpace + '/' + cleanUsername(usr.username);
        } catch (e) {
            return null;
        }
    };

    /**
     * Get the registry instance belongs to logged in user.
     * @return {*}
     */
    user.userRegistry = function (session) {
        try {
            return session.get(USER_REGISTRY);
        } catch (e) {
            return null;
        }
    };

    /**
     * Logs out the currently logged in user.
     */
    user.logout = function () {
        var usr = server.current(session),
            event = require('event'),
            opts = server.configs(usr.tenantId);
        if (opts.logout) {
            opts.logout(usr, session);
        }
        event.emit('logout', usr.tenantId, usr, session);
    };

    /**
     * Checks whether the specified username already exists.
     * @param username ruchira@ruchira.com(multi-tenanted) or ruchira
     * @return {*}
     */
    user.userExists = function (username) {
        var carbon = require('carbon'),
            usr = carbon.server.tenantUser(username);
        return server.userManager(usr.tenantId).userExists(usr.username);
    };

    user.register = function (username, password) {
        var carbon = require('carbon'),
            event = require('event'),
            usr = carbon.server.tenantUser(username),
            um = server.userManager(usr.tenantId);
        if (!user.configs(usr.tenantId)) {
            event.emit('tenantLoad', usr.tenantId);
        }

        um.addUser(usr.username, password, []);
        usr = um.getUser(usr.username);
        event.emit('userRegister', usr.tenantId, usr);
        //login(username, password);
    };

    user.loadTenant = function(username){
        var carbon = require('carbon'),
            event = require('event'),
            usr = carbon.server.tenantUser(username);
        if (!user.configs(usr.tenantId)) {
            event.emit('tenantLoad', usr.tenantId);
        }

    };

    user.emitLogin = function (username){
        var event = require('event');
        var usr = carbon.server.tenantUser(username);
        var um = server.userManager(usr.tenantId);
        var usr = um.getUser(usr.username);
        event.emit('login', usr.tenantId, usr, session);
    }

    user.loginWithSAML = function (username) {
        return user.permitted(username, session);
    };

    user.removeTenantDomainFromUsername = function(username){
        var userCoreUtil = new org.wso2.carbon.user.core.util.UserCoreUtil();
        return userCoreUtil.removeDistinguishedName(username);
    }
}(server, user));<commit_msg>fixing email user login issue<commit_after>/*
 *  Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you 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.
 *
 */
var user = {};
(function (server, user) {

    var USER_REGISTRY = 'server.user.registry';

    var USER_SPACE = 'server.user.space';

    var USER_ROLE_PREFIX = 'Internal/private_';

    var cleanUsername = function (username) {
        /**
         * this is a one-way hash function, @ is replaced if the user name is an email
         * if the user name is coming from a secondery user store it will be second.com/user hence
         * "/" will be replaced.
         */

        return username.replace('@', ':').replace('/', ':');
    };

    user.cleanUsername=function(username){
        return cleanUsername(username);
    };

    user.privateRole = function (username) {
        return USER_ROLE_PREFIX + cleanUsername(username);
    };

    user.USER_OPTIONS = 'server.user.options';

    /**
     * Initializes the user environment for the specified tenant. If it is already initialized, then will be skipped.
     */
    user.init = function (options) {
        var event = require('event');
        event.on('tenantCreate', function (tenantId) {

        });

        event.on('tenantLoad', function (tenantId) {
            var registry = server.systemRegistry(tenantId);
            user.configs(tenantId, JSON.parse(registry.content(options.tenantConfigs)));
        });

        event.on('tenantUnload', function (tenantId) {

        });

        event.on('login', function (tenantId, usr, session) {
            var space,
                carbon = require('carbon');
            server.current(session, usr);
            session.put(USER_REGISTRY, new carbon.registry.Registry(server.instance(), {
                username: usr.username,
                tenantId: tenantId
            }));
            space = user.userSpace(usr);
            session.put(USER_SPACE, space);
            if (!usr.isAuthorized(space, carbon.registry.actions.PUT)) {
                event.emit('userRegister', tenantId, usr);
            }
        });

        event.on('logout', function (tenantId, usr, session) {
            server.current(session, null);
            session.remove(USER_SPACE);
            session.remove(USER_REGISTRY);
        });

        event.on('userRegister', function (tenantId, usr) {
            var role, perms, r, p,
                log = new Log(),
                carbon = require('carbon'),
                event = require('event'),
                um = server.userManager(usr.tenantId),
                opts = user.configs(usr.tenantId),
                space = user.userSpace(usr),
                registry = server.systemRegistry(tenantId);
            if (!registry.exists(space)) {
                registry.put(space, {
                    collection: true
                });
                if (log.isDebugEnabled()) {
                    log.debug('user space was created for user : ' + usr.username + ' at ' + space);
                }
            }
            role = user.privateRole(usr.username);
            perms = {};
            perms[space] = [
                carbon.registry.actions.GET,
                carbon.registry.actions.PUT,
                carbon.registry.actions.DELETE,
                carbon.registry.actions.AUTHORIZE
            ];
            p = opts.permissions.login;
            for (r in p) {
                if (p.hasOwnProperty(r)) {
                    perms[r] = p[r];
                }
            }
            if (!um.roleExists(role)) {
                um.addRole(role, [], perms);
            }
            if (!usr.hasRoles([role])) {
                usr.addRoles([role]);
            }
            um.authorizeRole(user.privateRole(usr.username), perms);
            if (log.isDebugEnabled()) {
                log.debug('user ' + usr.username + ' was initialized and role ' + role +
                    ' was authorized to access user space ' + space);
            }
        });
    };

    /**
     * Returns user options of the tenant.
     * @return {Object}
     */
    user.configs = function (tenantId, configs) {
        var o = server.configs(tenantId);
        return configs ? (o[user.USER_OPTIONS] = configs) : o[user.USER_OPTIONS];
    };

    /**
     * Logs in a user to the store. Username might contains the domain part in case of MT mode.
     * @param username ruchira or ruchira@ruchira.com
     * @param password
     * @param session
     * @return {boolean}
     */
    user.login = function (username, password, session) {
        var carbon = require('carbon'),
            event = require('event'),
            serv = server.instance();
        if (!serv.authenticate(username, password)) {
            return false;
        }
        return user.permitted(username, session);
    };

    user.permitted = function (username, session) {
        //load the tenant if it hasn't been loaded yet.
        var opts, um, perms, perm, actions, length, i,
            authorized = false,
            carbon = require('carbon'),
            event = require('event'),
            usr = carbon.server.tenantUser(username);
        if (!user.configs(usr.tenantId)) {
            event.emit('tenantLoad', usr.tenantId);
        }

        opts = user.configs(usr.tenantId);
        um = server.userManager(usr.tenantId);
        usr = um.getUser(usr.username);
        usr.tenantDomain = carbon.server.tenantDomain({tenantId: usr.tenantId});
        perms = opts.permissions.login;
        L1:
            for (perm in perms) {
                if (perms.hasOwnProperty(perm)) {
                    actions = perms[perm];
                    var log = new Log();
                    length = actions.length;
                    for (i = 0; i < length; i++) {
                        if (usr.isAuthorized(perm, actions[i])) {
                            authorized = true;
                            break L1;
                        }
                    }
                }
            }
        if (!authorized) {
            return false;
        }
        event.emit('login', usr.tenantId, usr, session);
        return true;
    };

    /**
     * Checks whether the logged in user has permission to the specified action.
     * @param user
     * @param permission
     * @param action
     * @return {*}
     */
    user.isAuthorized = function (user, permission, action) {
        var um = server.userManager(user.tenantId);
        return um.getUser(user.username).isAuthorized(permission, action);
    };

    /**
     * Returns the user's registry space. This should be called once with the username,
     * then can be called without the username.
     * @param usr user object
     * @return {*}
     */
    user.userSpace = function (usr) {
        try {
            return user.configs(usr.tenantId).userSpace + '/' + cleanUsername(usr.username);
        } catch (e) {
            return null;
        }
    };

    /**
     * Get the registry instance belongs to logged in user.
     * @return {*}
     */
    user.userRegistry = function (session) {
        try {
            return session.get(USER_REGISTRY);
        } catch (e) {
            return null;
        }
    };

    /**
     * Logs out the currently logged in user.
     */
    user.logout = function () {
        var usr = server.current(session),
            event = require('event'),
            opts = server.configs(usr.tenantId);
        if (opts.logout) {
            opts.logout(usr, session);
        }
        event.emit('logout', usr.tenantId, usr, session);
    };

    /**
     * Checks whether the specified username already exists.
     * @param username ruchira@ruchira.com(multi-tenanted) or ruchira
     * @return {*}
     */
    user.userExists = function (username) {
        var carbon = require('carbon'),
            usr = carbon.server.tenantUser(username);
        return server.userManager(usr.tenantId).userExists(usr.username);
    };

    user.register = function (username, password) {
        var carbon = require('carbon'),
            event = require('event'),
            usr = carbon.server.tenantUser(username),
            um = server.userManager(usr.tenantId);
        if (!user.configs(usr.tenantId)) {
            event.emit('tenantLoad', usr.tenantId);
        }

        um.addUser(usr.username, password, []);
        usr = um.getUser(usr.username);
        event.emit('userRegister', usr.tenantId, usr);
        //login(username, password);
    };

    user.loadTenant = function(username){
        var carbon = require('carbon'),
            event = require('event'),
            usr = carbon.server.tenantUser(username);
        if (!user.configs(usr.tenantId)) {
            event.emit('tenantLoad', usr.tenantId);
        }

    };

    user.emitLogin = function (username){
        var event = require('event');
        var usr = carbon.server.tenantUser(username);
        var um = server.userManager(usr.tenantId);
        var usr = um.getUser(usr.username);
        event.emit('login', usr.tenantId, usr, session);
    }

    user.loginWithSAML = function (username) {
        return user.permitted(username, session);
    };

    user.removeTenantDomainFromUsername = function(username){
        //TODO need to fix removeDomainFromName within usercore-util
        var lastIndex = username.lastIndexOf("@");
            if(lastIndex != -1){
                username = username.substring(0, lastIndex);
            }
        return username;
    }
}(server, user));<|endoftext|>