<commit_before>(function(window) {

	// Check for Zumo
	if (!Zumo || !ZumoExt)
		return;

	// *** HANDLER MANAGER DECORATIONS

	var bindHandler = function(type, handler, target) {
		target = target || $("body");
        var $target = $(target);
        if ($target.length > 0) {
		    $(target).on(type, handler);
            return true;
        } else {
            return false;
        }
	};

	var unbindHandler = function(type, handler, target) {
		target = target || window;
        var $target = $(target);
        if ($target.length > 0) {
            $target.off(type, handler);
            return true;
        } else {
            return false;
        }
	};

	ZumoExt.addHandlerBinder(bindHandler, unbindHandler, true);

	// *** SELECTOR DECORATIONS

	var selector = function(selector, container) {
		return $(selector, container)[0];
	};

	ZumoExt.setSelector(selector);

	// *** STATE MANAGERS

	var StateManagers = {

		init: function() {

			// *** FADE CLASS

			var Fade = function(target, session) {
				Zumo.StateManagers.BaseIo3Manager.call(this, target, session);
			};

			Fade.prototype = {

				_doIn: function() {
					var that = this;
					var $target = $(this.target);
					$target.css("display", "none");
					$target.fadeIn("slow", function() {
						that.setState(Zumo.StateManagers.STATE_ON);
					});
				},

				_doOut: function() {
					var that = this;
					$(this.target).fadeOut("slow", function() {
						that.setState(Zumo.StateManagers.STATE_OFF);
					});
				}

			};

			// *** INIT

			Zumo.ObjectUtils.extend(Fade, Zumo.StateManagers.BaseIo3Manager);
			//TODO: Check whether it is possible to allow register managers not starting with _
			Zumo.registerStateManager("_$fade", Fade);

		}

	};

	StateManagers.init();

    // *** CONF PARSERS

    var domConfParser = function(source) {

        var conf = {},
            mergeAttributes,
            parsePageBlock;

        if (typeof source != "object" || typeof source.getElementsByTagName != "function" || (source.firstChild && source.firstChild.nodeName == "zumo"))
            return null;

        mergeAttributes = function(o, element, list) {
            for (var i = 0; i < list.length; i++) {
                var name = list[i];
                var value = $(element).attr("data-" + name);
                if (value)
                    o[name] = value;
            }
        };

        parsePageBlock = function(element) {

            var $element = $(element),
                context = {},
                depends,
                handlers,
                handlerList,
                handlerValues,
                handler,
                i;

            mergeAttributes(context, element, ["type", "mediator", "container", "manager", "title"]);
            context.target = element;

            depends = $element.attr("data-depends");
            if (depends) {
                context.depends = depends.replace(/\s/g, " ").split(" ");
            } else {
                context.depends = [];
            }

            context.handlers = [];
            handlers = $element.attr("data-handlers");
            if (handlers) {
                handlerList = handlers.split(",");
                for (i = 0; i < handlerList.length; i++) {
                    handlerValues = handlerList[i].replace(/\s/g, "").split(":");
                    if (handlerValues.length > 1) {
                        handler = {
                            target: handlerValues[0],
                            type: handlerValues[1]
                        }
                    } else {
                        handler = {
                            type: handlerValues[0]
                        }
                    }
                    context.handlers.push(handler);
                }
            }

            return context;

        };

        conf.views = {
            pages: [],
            blocks: []
        };
        conf.commands = [];

        $("*[data-page]", source).each(function() {
            var context = parsePageBlock(this);
            context.id = $(this).attr("data-page");
            context.node = "page";
            conf.views.pages.push(context);
        });

        $("*[data-block]", source).each(function() {
            var context = parsePageBlock(this);
            context.id = $(this).attr("data-block");
            context.node = "block";
            conf.views.blocks.push(context);
        });

        return conf;

    };

    ZumoExt.addConfParser(domConfParser);

})(this);<commit_msg>Added loader master om jquery plugin<commit_after>(function(window) {

	// Check for Zumo
	if (!Zumo || !ZumoExt)
		return;

	// *** HANDLER MANAGER DECORATIONS

	var bindHandler = function(type, handler, target) {
		target = target || $("body");
        var $target = $(target);
        if ($target.length > 0) {
		    $(target).on(type, handler);
            return true;
        } else {
            return false;
        }
	};

	var unbindHandler = function(type, handler, target) {
		target = target || window;
        var $target = $(target);
        if ($target.length > 0) {
            $target.off(type, handler);
            return true;
        } else {
            return false;
        }
	};

	ZumoExt.addHandlerBinder(bindHandler, unbindHandler, true);

	// *** SELECTOR DECORATIONS

	var selector = function(selector, container) {
		return $(selector, container)[0];
	};

	ZumoExt.setSelector(selector);

	// *** VIEW MASTERS

    var $Loader = function(context, request, session, stateManager) {
        Zumo.ViewMasters.AbstractMaster.call(this, context, request, session, stateManager); // Call super
        // --
        // Implementing:
        // this.$container = null;
    };

    $Loader.prototype = {

        display: function() {

            Zumo.ViewMasters.AbstractMaster.prototype.display.apply(this, arguments); // Call super

            var that = this;

            this.$container = $(this.container);
            this.$container.load(this.context.target, function() {
                that.init();
            });

        },

        destroy: function() {
            Zumo.ViewMasters.AbstractMaster.prototype.destroy.apply(this, arguments); // Call super
            this.$container.clear();
        },

        init: function() {
            Zumo.ViewMasters.AbstractMaster.prototype.init.apply(this, arguments); // Call super
        },

        clear: function() {
            Zumo.ViewMasters.AbstractMaster.prototype.clear.apply(this, arguments); // Call super
        },

        onStateChange: function(target, state) {
            Zumo.ViewMasters.AbstractMaster.prototype.onStateChange.apply(this, arguments); // Call super
        },

        // Default event handlers
        onDisplay: function(master) {},
        onClear: function(master) {},
        onInit: function(master) {},
        onIn: function(master) {},
        onOn: function(master) {},
        onOut: function(master) {},
        onOff: function(master) {}

    };

    Zumo.registerViewMaster("_$loader", $Loader);

	// *** STATE MANAGERS

	var StateManagers = {

		init: function() {

			// *** FADE CLASS

			var Fade = function(target, session) {
				Zumo.StateManagers.BaseIo3Manager.call(this, target, session);
			};

			Fade.prototype = {

				_doIn: function() {
					var that = this;
					var $target = $(this.target);
					$target.css("display", "none");
					$target.fadeIn("slow", function() {
						that.setState(Zumo.StateManagers.STATE_ON);
					});
				},

				_doOut: function() {
					var that = this;
					$(this.target).fadeOut("slow", function() {
						that.setState(Zumo.StateManagers.STATE_OFF);
					});
				}

			};

			// *** INIT

			Zumo.ObjectUtils.extend(Fade, Zumo.StateManagers.BaseIo3Manager);
			//TODO: Check whether it is possible to allow register managers not starting with _
			Zumo.registerStateManager("_$fade", Fade);

		}

	};

	StateManagers.init();

    // *** CONF PARSERS

    var domConfParser = function(source) {

        var conf = {},
            mergeAttributes,
            parsePageBlock;

        if (typeof source != "object" || typeof source.getElementsByTagName != "function" || (source.firstChild && source.firstChild.nodeName == "zumo"))
            return null;

        mergeAttributes = function(o, element, list) {
            for (var i = 0; i < list.length; i++) {
                var name = list[i];
                var value = $(element).attr("data-" + name);
                if (value)
                    o[name] = value;
            }
        };

        parsePageBlock = function(element) {

            var $element = $(element),
                context = {},
                depends,
                handlers,
                handlerList,
                handlerValues,
                handler,
                i;

            mergeAttributes(context, element, ["type", "mediator", "container", "manager", "title"]);
            context.target = element;

            depends = $element.attr("data-depends");
            if (depends) {
                context.depends = depends.replace(/\s/g, " ").split(" ");
            } else {
                context.depends = [];
            }

            context.handlers = [];
            handlers = $element.attr("data-handlers");
            if (handlers) {
                handlerList = handlers.split(",");
                for (i = 0; i < handlerList.length; i++) {
                    handlerValues = handlerList[i].replace(/\s/g, "").split(":");
                    if (handlerValues.length > 1) {
                        handler = {
                            target: handlerValues[0],
                            type: handlerValues[1]
                        }
                    } else {
                        handler = {
                            type: handlerValues[0]
                        }
                    }
                    context.handlers.push(handler);
                }
            }

            return context;

        };

        conf.views = {
            pages: [],
            blocks: []
        };
        conf.commands = [];

        $("*[data-page]", source).each(function() {
            var context = parsePageBlock(this);
            context.id = $(this).attr("data-page");
            context.node = "page";
            conf.views.pages.push(context);
        });

        $("*[data-block]", source).each(function() {
            var context = parsePageBlock(this);
            context.id = $(this).attr("data-block");
            context.node = "block";
            conf.views.blocks.push(context);
        });

        return conf;

    };

    ZumoExt.addConfParser(domConfParser);

})(this);<|endoftext|>


<commit_before>define(function(require) {
    "use strict";

    var Model = require("./models/model");
    var FunctionHelper = require("./helpers/function-helper");
    var ModelHelper = require("./helpers/model-helper");

    var _singleton = null;

    var ModelModule = function(App) {
        //Public instance members
        var ModelModule = {
            /*
                @function create

                Creates a Model with the specified attributes, constructor and inheritance. Note that inheritancer and
                return are handled by AppCore and the provided constructor does not need to include them.

                @param {string} name                The desired model name
                @param {string[]} attributes        The desired class attributes
                @param [{function}] constructor     The desired class constructor
                @param [{object}] parentClass       The desired parent class to inherit from

                @return {object}
            */
            create: function(name, attributes, constructor, parentClass) {
                parentClass = parentClass ? parentClass : Model;

                //Create the child class constructor. Use a verbose method for performance optimization.
                var childClass;

                if (constructor) {
                    childClass = parentClass === Model ? function() {
                        parentClass.apply(this, [name, attributes]);
                        constructor.apply(this, arguments);

                        return this;
                    } :
                    function() {
                        parentClass.apply(this, arguments);
                        constructor.apply(this, arguments);

                        return this;
                    };
                }
                else {
                    var defaultConstructor = function() {
                        var values = {};

                        for (var i = 0, length = arguments.length; i < length; i++) {
                            values[attributes[i]] = arguments[i];
                        }

                        this.set(values);
                    };

                    childClass = parentClass === Model ? function() {
                        parentClass.apply(this, [name, attributes]);
                        defaultConstructor.apply(this, arguments);

                        return this;
                    } :
                    function() {
                        parentClass.apply(this, arguments);
                        defaultConstructor.apply(this, arguments);

                        return this;
                    };
                }

                //Implement inheritance
                childClass.prototype = Object.create(parentClass.prototype);

                //Initialize model methods
                Model.init(childClass);

                //Generate getter and setter methods
                var attribute;

                for (var i = 0, length = attributes.length; i < length; i++) {
                    attribute = attributes[i];

                    //jshint -W083
                    (function(attribute) {
                        childClass.prototype[ModelHelper.getGetter(attribute)] = function() {
                            return this.get(attribute);
                        };

                        childClass.prototype[ModelHelper.getSetter(attribute)] = function(value) {
                            this.set(attribute, value);
                            App.View.refresh(this);
                        };
                    })(attributes[i]);
                    //jshint +W083
                }

                childClass.prototype.set = FunctionHelper.override(childClass.prototype.set,
                    function(originalFunction, context, args) {
                    originalFunction.apply(context, args);
                    App.View.refresh(context);
                });

                childClass.prototype.setId = FunctionHelper.override(childClass.prototype.setId,
                    function(originalFunction, context, args) {
                    originalFunction.apply(context, args);
                    App.View.refresh(context);
                });

                return childClass;
            }
        };

        return ModelModule;
    };

    return (function() {
        if (_singleton === null || _singleton === undefined) {
            _singleton = ModelModule;
        }

        return _singleton;
    })();
});<commit_msg>Core: Fixed issue with default constructor created by Model.create() method.<commit_after>define(function(require) {
    "use strict";

    var Model = require("./models/model");
    var FunctionHelper = require("./helpers/function-helper");
    var ModelHelper = require("./helpers/model-helper");

    var _singleton = null;

    var ModelModule = function(App) {
        //Public instance members
        var ModelModule = {
            /*
                @function create

                Creates a Model with the specified attributes, constructor and inheritance. Note that inheritancer and
                return are handled by AppCore and the provided constructor does not need to include them.

                @param {string} name                The desired model name
                @param {string[]} attributes        The desired class attributes
                @param [{function}] constructor     The desired class constructor
                @param [{object}] parentClass       The desired parent class to inherit from

                @return {object}
            */
            create: function(name, attributes, constructor, parentClass) {
                parentClass = parentClass ? parentClass : Model;

                //Create the child class constructor. Use a verbose method for performance optimization.
                var childClass;

                if (constructor) {
                    childClass = parentClass === Model ? function() {
                        parentClass.apply(this, [name, attributes]);
                        constructor.apply(this, arguments);

                        return this;
                    } :
                    function() {
                        parentClass.apply(this, arguments);
                        constructor.apply(this, arguments);

                        return this;
                    };
                }
                else {
                    var defaultConstructor = function() {
                        var values = {};

                        if (arguments) {
                            for (var i = 0, length = attributes.length; i < length; i++) {
                                values[attributes[i]] = arguments[i] !== undefined ? arguments[i] : null;
                            }
                        }

                        this.set(values);
                    };

                    childClass = parentClass === Model ? function() {
                        parentClass.apply(this, [name, attributes]);
                        defaultConstructor.apply(this, arguments);

                        return this;
                    } :
                    function() {
                        parentClass.apply(this, arguments);
                        defaultConstructor.apply(this, arguments);

                        return this;
                    };
                }

                //Implement inheritance
                childClass.prototype = Object.create(parentClass.prototype);

                //Initialize model methods
                Model.init(childClass);

                //Generate getter and setter methods
                var attribute;

                for (var i = 0, length = attributes.length; i < length; i++) {
                    attribute = attributes[i];

                    //jshint -W083
                    (function(attribute) {
                        childClass.prototype[ModelHelper.getGetter(attribute)] = function() {
                            return this.get(attribute);
                        };

                        childClass.prototype[ModelHelper.getSetter(attribute)] = function(value) {
                            this.set(attribute, value);
                            App.View.refresh(this);
                        };
                    })(attributes[i]);
                    //jshint +W083
                }

                childClass.prototype.set = FunctionHelper.override(childClass.prototype.set,
                    function(originalFunction, context, args) {
                    originalFunction.apply(context, args);
                    App.View.refresh(context);
                });

                childClass.prototype.setId = FunctionHelper.override(childClass.prototype.setId,
                    function(originalFunction, context, args) {
                    originalFunction.apply(context, args);
                    App.View.refresh(context);
                });

                return childClass;
            }
        };

        return ModelModule;
    };

    return (function() {
        if (_singleton === null || _singleton === undefined) {
            _singleton = ModelModule;
        }

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


<commit_before>// Opening for events
const eventTitles = getElementsByClassName('event-title')
const eventSubtitles = getElementsByClassName('event-subtitle')
const eventDetails = getElementsByClassName('event-details')
for (let i = 0; i < eventTitles.length; i++) {
	// Fade in
	eventTitles[i].classList.add('fade-move')
	eventSubtitles[i].classList.add('fade-move')
	eventDetails[i].classList.add('fade-move')
	// Email signup form
	// If background image is so complex that email signup form needs a dark background instead of a transparent background...
	const emailBox = getElementsByClassName('email-box')[i]
	// emailBox with class `email container background` has conditional visibility in Webflow, so Webflow tags a new class called `w-condition-invisible` if collection determines it’s invisible
	const visible = emailBox.querySelector('div.email-container-background.w-condition-invisible') === null
	changeEmailContainerBackground({ visible })
}

// Reg Form elements
const regFormButtons = getElementsByClassName('button register')
const regFormBg = getElementByClassName('reg-form-background')
const regFormContainer = getElementByClassName('reg-form-container')
const regForm = getElementByClassName('reg-form')

const showRegForm = () => {
	// Prevent background to scroll
	document.body.style.overflow = 'hidden'
	// Unhide reg form background
	showElement(regFormBg)
	setTimeout(() => {
		// Fade in background after 100ms once unhidden
		fadeInElement(regFormBg)
		setTimeout(() => {
			// Once background has successfully faded in after 200ms, scroll to top to prevent fade error on Chrome.
			window.scrollTo(0, 0)
			setTimeout(() => {
				// Once scroll to top has occurred, unhide reg form...
				showElement(regFormContainer)
				// ...scroll to top of reg form...
				regFormContainer.scrollTop = 0
				// ...and fade in.
				setTimeout(() => fadeInElement(regFormContainer), 100)
			}, 100)
		}, 200)
	}, 100)
}

const closeRegForm = () => {
	// Reallow background to scroll
	document.body.style.overflow = 'visible'
	// Fade out elements
	fadeOutElement(regFormBg)
	fadeOutElement(regFormContainer)
	// Hide elements after fade out
	setTimeout(() => {
		hideElement(regFormBg)
		hideElement(regFormContainer)
	}, 200)
}

regFormContainer.onscroll = () => {
	const elements = regForm.querySelectorAll('input, textarea, div')
	for (let i = 0; i < elements.length; i++) {
		const element = elements[i]
		element.style.webkitTransform = 'translateZ(0)'
	}
}

// Event listener for if reg form is opened...
for (let i = 0; i < regFormButtons.length; i++) {
	onClick(regFormButtons[i], () => showRegForm())
}
// ...and closed.
const regFormClose = getElementByClassName('reg-form-close')
onClick(regFormClose, () => closeRegForm())

// Event summary “Read more...” expansion
getElementByClassName('text read-more').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)
})<commit_msg>004 - regFormContainer onscroll fix attempt<commit_after>// Opening for events
const eventTitles = getElementsByClassName('event-title')
const eventSubtitles = getElementsByClassName('event-subtitle')
const eventDetails = getElementsByClassName('event-details')
for (let i = 0; i < eventTitles.length; i++) {
	// Fade in
	eventTitles[i].classList.add('fade-move')
	eventSubtitles[i].classList.add('fade-move')
	eventDetails[i].classList.add('fade-move')
	// Email signup form
	// If background image is so complex that email signup form needs a dark background instead of a transparent background...
	const emailBox = getElementsByClassName('email-box')[i]
	// emailBox with class `email container background` has conditional visibility in Webflow, so Webflow tags a new class called `w-condition-invisible` if collection determines it’s invisible
	const visible = emailBox.querySelector('div.email-container-background.w-condition-invisible') === null
	changeEmailContainerBackground({ visible })
}

// Reg Form elements
const regFormButtons = getElementsByClassName('button register')
const regFormBg = getElementByClassName('reg-form-background')
const regFormContainer = getElementByClassName('reg-form-container')
const regForm = getElementByClassName('reg-form')

const showRegForm = () => {
	// Prevent background to scroll
	document.body.style.overflow = 'hidden'
	// Unhide reg form background
	showElement(regFormBg)
	setTimeout(() => {
		// Fade in background after 100ms once unhidden
		fadeInElement(regFormBg)
		setTimeout(() => {
			// Once background has successfully faded in after 200ms, scroll to top to prevent fade error on Chrome.
			window.scrollTo(0, 0)
			setTimeout(() => {
				// Once scroll to top has occurred, unhide reg form...
				showElement(regFormContainer)
				// ...scroll to top of reg form...
				regFormContainer.scrollTop = 0
				// ...and fade in.
				setTimeout(() => fadeInElement(regFormContainer), 100)
			}, 100)
		}, 200)
	}, 100)
}

const closeRegForm = () => {
	// Reallow background to scroll
	document.body.style.overflow = 'visible'
	// Fade out elements
	fadeOutElement(regFormBg)
	fadeOutElement(regFormContainer)
	// Hide elements after fade out
	setTimeout(() => {
		hideElement(regFormBg)
		hideElement(regFormContainer)
	}, 200)
}

regFormContainer.onscroll = () => {
	const elements = regForm.querySelectorAll('input, textarea, div')
	for (let i = 0; i < elements.length; i++) {
		const element = elements[i]
		element.style.webkitTransform = 'translateZ(0)'
		element.style.opacity = '1.0'
	}
}

// Event listener for if reg form is opened...
for (let i = 0; i < regFormButtons.length; i++) {
	onClick(regFormButtons[i], () => showRegForm())
}
// ...and closed.
const regFormClose = getElementByClassName('reg-form-close')
onClick(regFormClose, () => closeRegForm())

// Event summary “Read more...” expansion
getElementByClassName('text read-more').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)
})<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { connect } from 'react-redux'
import { push } from 'connected-react-router'

import { CuratedEventListItem, StaticPage } from '../components'
import { asInfiniteListCalendar } from '../containers'
import { translate } from '../../../common/services/i18n'
import { withConfig } from '../containers'

const WrappedInfiniteList = asInfiniteListCalendar(CuratedEventListItem)

class Calendar extends Component {
  static propTypes = {
    config: PropTypes.object.isRequired,
    isActive: PropTypes.bool.isRequired,
    isAdmin: PropTypes.bool.isRequired,
    isAuthenticated: PropTypes.bool.isRequired,
    isParticipant: PropTypes.bool.isRequired,
    push: PropTypes.func.isRequired,
  }

  onClick(item) {
    this.props.push(`/events/${item.slug}`)
  }

  onEditClick(item) {
    this.props.push(`/events/${item.slug}/edit`)
  }

  onPreviewClick() {
    this.props.push('/tickets')
  }

  renderItemsList() {
    if ((!this.props.isAuthenticated || !this.props.isActive) && this.props.config.festivalTicketPrice !== 0) {
      return (
        <WrappedInfiniteList
          resourceName="preview"
          onClick={this.onPreviewClick}
        />
      )
    }

    return (
      <WrappedInfiniteList
        resourceName="events"
        onClick={this.onClick}
        onEditClick={this.onEditClick}
      />
    )
  }

  renderCreateButton() {
    if (
      !(this.props.isParticipant || this.props.isAdmin) ||
      !this.props.isAuthenticated
    ) {
      return null
    }

    return (
      <Link className="button button--green" to="/new/event">
        { translate('views.events.createNewButton') }
      </Link>
    )
  }

  renderText() {
    if ((!this.props.isAuthenticated || !this.props.isActive) && this.props.config.festivalTicketPrice !== 0) {
      return <StaticPage hideTitle={true} slug="calendar-public" />
    }

    return <StaticPage hideTitle={true} slug="calendar" />
  }

  render() {
    return (

{ translate('views.events.calendarTitle') }

        { this.renderText() }
        { this.renderCreateButton() }

        { this.renderItemsList() }

    )
  }

  constructor(props) {
    super(props)

    this.onClick = this.onClick.bind(this)
    this.onEditClick = this.onEditClick.bind(this)
    this.onPreviewClick = this.onPreviewClick.bind(this)
  }
}

function mapStateToProps(state) {
  return {
    ...state.auth,
    ...state.user,
    ...state.meta,
  }
}

export default connect(
  mapStateToProps, {
    push,
  }
)(withConfig(Calendar))
<commit_msg>Render CalendarMap in CalendarView<commit_after>import PropTypes from 'prop-types'
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { connect } from 'react-redux'
import { push } from 'connected-react-router'
import { DateTime } from 'luxon'

import { CalendarMap, CuratedEventListItem, StaticPage } from '../components'
import { asInfiniteListCalendar } from '../containers'
import { translate } from '../../../common/services/i18n'
import { withConfig } from '../containers'

const WrappedInfiniteList = asInfiniteListCalendar(CuratedEventListItem)

class Calendar extends Component {
  static propTypes = {
    config: PropTypes.object.isRequired,
    isActive: PropTypes.bool.isRequired,
    isAdmin: PropTypes.bool.isRequired,
    isAuthenticated: PropTypes.bool.isRequired,
    isParticipant: PropTypes.bool.isRequired,
    listItems: PropTypes.array.isRequired,
    push: PropTypes.func.isRequired,
  }

  static defaultProps = {
    listItems: [],
  }

  onClick(item) {
    this.props.push(`/events/${item.slug}`)
  }

  onEditClick(item) {
    this.props.push(`/events/${item.slug}/edit`)
  }

  onPreviewClick() {
    this.props.push('/tickets')
  }

  renderItemsList() {
    if ((!this.props.isAuthenticated || !this.props.isActive) && this.props.config.festivalTicketPrice !== 0) {
      return (
        <WrappedInfiniteList
          resourceName="preview"
          onClick={this.onPreviewClick}
        />
      )
    }

    return (
      <WrappedInfiniteList
        resourceName="events"
        onClick={this.onClick}
        onEditClick={this.onEditClick}
      />
    )
  }

  renderCreateButton() {
    if (
      !(this.props.isParticipant || this.props.isAdmin) ||
      !this.props.isAuthenticated
    ) {
      return null
    }

    return (
      <Link className="button button--green" to="/new/event">
        { translate('views.events.createNewButton') }
      </Link>
    )
  }

  renderText() {
    if ((!this.props.isAuthenticated || !this.props.isActive) && this.props.config.festivalTicketPrice !== 0) {
      return <StaticPage hideTitle={true} slug="calendar-public" />
    }

    return <StaticPage hideTitle={true} slug="calendar" />
  }

  renderMap() {
    if ((!this.props.isAuthenticated || !this.props.isActive) && this.props.config.festivalTicketPrice !== 0) {
      return null
    }

    const allEvents = this.props.listItems
    let uniqueVenues = []

    if (allEvents.length === 0) {
      return null
    }

    uniqueVenues = allEvents
      .map(event => event.placeId)
      .map((event, index, final) => final.indexOf(event) === index && index)
      .filter(event => allEvents[event]).map(event => allEvents[event].place)
      .filter(place => place.mode !== 'virtual')

    const mapVenuePlots = uniqueVenues.map(venue => {
      const venueEvents = allEvents.reduce((result, event) => {
        if (venue.id === event.placeId) {
          const time = DateTime.fromISO(event.slots[0].from).toFormat('T DDDD')
          result.push({
            title: event.title,
            time: time,
            imageUrl: event.images.length > 0 ? event.images[0].smallImageUrl : null,
            slug: event.slug,
          })
        }
        return result
      }, [])

      return {
        city: venue.city,
        cityCode: venue.cityCode,
        country: venue.country,
        key: venue.id,
        latitude: venue.latitude,
        longitude: venue.longitude,
        mode: venue.mode,
        street: venue.street,
        place: venue.title,
        events: venueEvents,
      }
    })
    return (

        <CalendarMap initialCenter= { { lat: this.props.config.defaultLatitude, lng: this.props.config.defaultLongitude } } plots={mapVenuePlots} />

    )
  }

  render() {
    return (

{ translate('views.events.calendarTitle') }

        { this.renderText() }
        { this.renderCreateButton() }

        { this.renderMap() }
        { this.renderItemsList() }

    )
  }

  constructor(props) {
    super(props)

    this.onClick = this.onClick.bind(this)
    this.onEditClick = this.onEditClick.bind(this)
    this.onPreviewClick = this.onPreviewClick.bind(this)
  }
}

function mapStateToProps(state) {
  return {
    ...state.auth,
    ...state.user,
    ...state.meta,
    ...state.infiniteList.events,
  }
}

export default connect(
  mapStateToProps, {
    push,
  }
)(withConfig(Calendar))
<|endoftext|>


<commit_before>// 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.

define([
       "app",

       // Modules
       "modules/fauxton/base"
],

function(app, Fauxton) {
  var FauxtonAPI = app.module();

  FauxtonAPI.moduleExtensions = {
    Routes: {
    }
  };

  FauxtonAPI.addonExtensions = {
    initialize: function() {}
  };

  // List of JSHINT errors to ignore
  // Gets around problem of anonymous functions not being a valid statement
  FauxtonAPI.excludedViewErrors = [
    "Missing name in function declaration."
  ];

  FauxtonAPI.isIgnorableError = function(msg) {
    return _.contains(FauxtonAPI.excludedViewErrors, msg);
  };

  FauxtonAPI.View = Backbone.View.extend({
    // This should return an array of promises, an empty array, or null
    establish: function() {
      return null;
    },

    hasRendered: function () {
      return !!this.__manager__.hasRendered;
    },

    forceRender: function () {
      this.__manager__.hasRendered = false;
    }
  });

  FauxtonAPI.navigate = function(url) {
    Backbone.history.navigate(url, true);
  };

  FauxtonAPI.addHeaderLink = function(link) {
    app.masterLayout.navBar.addLink(link);
  };

  FauxtonAPI.Deferred = function() {
    return $.Deferred();
  };

  FauxtonAPI.when = function (deferreds) {
    if (deferreds instanceof Array) {
      return $.when.apply(null, deferreds);
    }

    return $.when(deferreds);
  },

  FauxtonAPI.addRoute = function(route) {
    app.router.route(route.route, route.name, route.callback);
  };

  FauxtonAPI.triggerRouteEvent = function (routeEvent, args) {
    app.router.triggerRouteEvent("route:"+routeEvent, args);
  };

  FauxtonAPI.module = function(extra) {
    return app.module(_.extend(FauxtonAPI.moduleExtensions, extra));
  };

  FauxtonAPI.addon = function(extra) {
    return FauxtonAPI.module(FauxtonAPI.addonExtensions, extra);
  };

  FauxtonAPI.addNotification = function(options) {
    options = _.extend({
      msg: "Notification Event Triggered!",
      type: "info",
      selector: "#global-notifications"
    }, options);
    var view = new Fauxton.Notification(options);

    return view.renderNotification();
  };

  FauxtonAPI.UUID = Backbone.Model.extend({
    initialize: function(options) {
      options = _.extend({count: 1}, options);
      this.count = options.count;
    },

    url: function() {
      return app.host + "/_uuids?count=" + this.count;
    },

    next: function() {
      return this.get("uuids").pop();
    }
  });

  FauxtonAPI.Session = Backbone.Model.extend({
    url: '/_session',

    user: function () {
      var userCtx = this.get('userCtx');

      if (!userCtx || !userCtx.name) { return null; }

      return {
        name: userCtx.name,
        roles: userCtx.roles
      };
    },

    fetchOnce: function (opt) {
      var options = _.extend({}, opt);

      if (!this._deferred || this._deferred.state() === "rejected" || options.forceFetch ) {
        this._deferred = this.fetch();
      }

      return this._deferred;
    },

    fetchUser: function (opt) {
      var that = this,
      currentUser = this.user();

      return this.fetchOnce(opt).then(function () {
        var user = that.user();

        // Notify anyone listening on these events that either a user has changed
        // or current user is the same
        if (currentUser !== user) {
          that.trigger('session:userChanged');
        } else {
          that.trigger('session:userFetched');
        }

        // this will return the user as a value to all function that calls done on this
        // eg. session.fetchUser().done(user) { .. do something with user ..}
        return user;
      });
    }
  });

  FauxtonAPI.setSession = function (newSession) {
    app.session = FauxtonAPI.session = newSession;
    return FauxtonAPI.session.fetchUser();
  };

  FauxtonAPI.setSession(new FauxtonAPI.Session());

  // This is not exposed externally as it should not need to be accessed or overridden
  var Auth = function (options) {
    this._options = options;
    this.initialize.apply(this, arguments);
  };

  // Piggy-back on Backbone's self-propagating extend function,
  Auth.extend = Backbone.Model.extend;

  _.extend(Auth.prototype, Backbone.Events, {
    authDeniedCb: function() {},

    initialize: function() {
      var that = this;
    },

    authHandlerCb : function (roles) {
      var deferred = $.Deferred();
      deferred.resolve();
      return deferred;
    },

    registerAuth: function (authHandlerCb) {
      this.authHandlerCb = authHandlerCb;
    },

    registerAuthDenied: function (authDeniedCb) {
      this.authDeniedCb = authDeniedCb;
    },

    checkAccess: function (roles) {
      var requiredRoles = roles || [],
      that = this;

      return FauxtonAPI.session.fetchUser().then(function (user) {
        return FauxtonAPI.when(that.authHandlerCb(FauxtonAPI.session, requiredRoles));
      });
    }
  });

  FauxtonAPI.auth = new Auth();

  FauxtonAPI.RouteObject = function(options) {
    this._options = options;

    this._configure(options || {});
    this.initialize.apply(this, arguments);
    this.addEvents();
  };

  // Piggy-back on Backbone's self-propagating extend function
  FauxtonAPI.RouteObject.extend = Backbone.Model.extend;

  var routeObjectOptions = ["views", "routes", "events", "roles", "crumbs", "layout", "apiUrl", "establish"];

  _.extend(FauxtonAPI.RouteObject.prototype, Backbone.Events, {
    // Should these be default vals or empty funcs?
    views: {},
    routes: {},
    events: {},
    crumbs: [],
    layout: "with_sidebar",
    apiUrl: null,
    renderedState: false,
    establish: function() {},
    route: function() {},
    roles: [],
    initialize: function() {}
  }, {

    renderWith: function(route, masterLayout, args) {
      var routeObject = this;

      // TODO: Can look at replacing this with events eg beforeRender, afterRender function and events
      this.route.call(this, route, args);

      // Only want to redo the template if its a full render
      if (!this.renderedState) {
        masterLayout.setTemplate(this.layout);
      }

      masterLayout.clearBreadcrumbs();
      var crumbs = this.get('crumbs');

      if (crumbs.length) {
        masterLayout.setBreadcrumbs(new Fauxton.Breadcrumbs({
          crumbs: crumbs
        }));
      }

      FauxtonAPI.when(this.establish()).done(function(resp) {
        _.each(routeObject.getViews(), function(view, selector) {
          if(view.hasRendered()) { return; }

          masterLayout.setView(selector, view);

          FauxtonAPI.when(view.establish()).then(function(resp) {
            masterLayout.renderView(selector);
          }, function(resp) {
            view.establishError = {
              error: true,
              reason: resp
            };
            masterLayout.renderView(selector);
          });

          var hooks = masterLayout.hooks[selector];

          _.each(hooks, function(hook){
            if (_.any(hook.routes, function(route){return route == boundRoute;})){
              hook.callback(view);
            }
          });
        });
      });

      if (this.get('apiUrl')) masterLayout.apiBar.update(this.get('apiUrl'));

      // Track that we've done a full initial render
      this.renderedState = true;
    },

    get: function(key) {
      return _.isFunction(this[key]) ? this[key]() : this[key];
    },

    addEvents: function(events) {
      events = events || this.get('events');
      _.each(events, function(method, event) {
        if (!_.isFunction(method) && !_.isFunction(this[method])) {
          throw new Error("Invalid method: "+method);
        }
        method = _.isFunction(method) ? method : this[method];

        this.on(event, method);
      }, this);
    },

    _configure: function(options) {
      _.each(_.intersection(_.keys(options), routeObjectOptions), function(key) {
        this[key] = options[key];
      }, this);
    },

    getView: function(selector) {
      return this.views[selector];
    },

    setView: function(selector, view) {
      this.views[selector] = view;
      return view;
    },

    getViews: function() {
      return this.views;
    },

    getRouteUrls: function () {
      return _.keys(this.get('routes'));
    },

    hasRoute: function (route) {
      if (this.get('routes')[route]) {
        return true;
      }
      return false;
    },

    routeCallback: function (route, args) {
      var routes = this.get('routes'),
      routeObj = routes[route],
      routeCallback;

      if (typeof routeObj === 'object') {
        routeCallback = this[routeObj.route];
      } else {
        routeCallback = this[routeObj];
      }

      routeCallback.apply(this, args);
    },

    getRouteRoles: function (routeUrl) {
      var route = this.get('routes')[routeUrl];

      if ((typeof route === 'object') && route.roles) {
        return route.roles;
      }

      return this.roles;
    }

  });

  app.fauxtonAPI = FauxtonAPI;
  return app.fauxtonAPI;
});
<commit_msg>Fix fauxton boundRoute bug<commit_after>// 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.

define([
       "app",

       // Modules
       "modules/fauxton/base"
],

function(app, Fauxton) {
  var FauxtonAPI = app.module();

  FauxtonAPI.moduleExtensions = {
    Routes: {
    }
  };

  FauxtonAPI.addonExtensions = {
    initialize: function() {}
  };

  // List of JSHINT errors to ignore
  // Gets around problem of anonymous functions not being a valid statement
  FauxtonAPI.excludedViewErrors = [
    "Missing name in function declaration."
  ];

  FauxtonAPI.isIgnorableError = function(msg) {
    return _.contains(FauxtonAPI.excludedViewErrors, msg);
  };

  FauxtonAPI.View = Backbone.View.extend({
    // This should return an array of promises, an empty array, or null
    establish: function() {
      return null;
    },

    hasRendered: function () {
      return !!this.__manager__.hasRendered;
    },

    forceRender: function () {
      this.__manager__.hasRendered = false;
    }
  });

  FauxtonAPI.navigate = function(url) {
    Backbone.history.navigate(url, true);
  };

  FauxtonAPI.addHeaderLink = function(link) {
    app.masterLayout.navBar.addLink(link);
  };

  FauxtonAPI.Deferred = function() {
    return $.Deferred();
  };

  FauxtonAPI.when = function (deferreds) {
    if (deferreds instanceof Array) {
      return $.when.apply(null, deferreds);
    }

    return $.when(deferreds);
  },

  FauxtonAPI.addRoute = function(route) {
    app.router.route(route.route, route.name, route.callback);
  };

  FauxtonAPI.triggerRouteEvent = function (routeEvent, args) {
    app.router.triggerRouteEvent("route:"+routeEvent, args);
  };

  FauxtonAPI.module = function(extra) {
    return app.module(_.extend(FauxtonAPI.moduleExtensions, extra));
  };

  FauxtonAPI.addon = function(extra) {
    return FauxtonAPI.module(FauxtonAPI.addonExtensions, extra);
  };

  FauxtonAPI.addNotification = function(options) {
    options = _.extend({
      msg: "Notification Event Triggered!",
      type: "info",
      selector: "#global-notifications"
    }, options);
    var view = new Fauxton.Notification(options);

    return view.renderNotification();
  };

  FauxtonAPI.UUID = Backbone.Model.extend({
    initialize: function(options) {
      options = _.extend({count: 1}, options);
      this.count = options.count;
    },

    url: function() {
      return app.host + "/_uuids?count=" + this.count;
    },

    next: function() {
      return this.get("uuids").pop();
    }
  });

  FauxtonAPI.Session = Backbone.Model.extend({
    url: '/_session',

    user: function () {
      var userCtx = this.get('userCtx');

      if (!userCtx || !userCtx.name) { return null; }

      return {
        name: userCtx.name,
        roles: userCtx.roles
      };
    },

    fetchOnce: function (opt) {
      var options = _.extend({}, opt);

      if (!this._deferred || this._deferred.state() === "rejected" || options.forceFetch ) {
        this._deferred = this.fetch();
      }

      return this._deferred;
    },

    fetchUser: function (opt) {
      var that = this,
      currentUser = this.user();

      return this.fetchOnce(opt).then(function () {
        var user = that.user();

        // Notify anyone listening on these events that either a user has changed
        // or current user is the same
        if (currentUser !== user) {
          that.trigger('session:userChanged');
        } else {
          that.trigger('session:userFetched');
        }

        // this will return the user as a value to all function that calls done on this
        // eg. session.fetchUser().done(user) { .. do something with user ..}
        return user;
      });
    }
  });

  FauxtonAPI.setSession = function (newSession) {
    app.session = FauxtonAPI.session = newSession;
    return FauxtonAPI.session.fetchUser();
  };

  FauxtonAPI.setSession(new FauxtonAPI.Session());

  // This is not exposed externally as it should not need to be accessed or overridden
  var Auth = function (options) {
    this._options = options;
    this.initialize.apply(this, arguments);
  };

  // Piggy-back on Backbone's self-propagating extend function,
  Auth.extend = Backbone.Model.extend;

  _.extend(Auth.prototype, Backbone.Events, {
    authDeniedCb: function() {},

    initialize: function() {
      var that = this;
    },

    authHandlerCb : function (roles) {
      var deferred = $.Deferred();
      deferred.resolve();
      return deferred;
    },

    registerAuth: function (authHandlerCb) {
      this.authHandlerCb = authHandlerCb;
    },

    registerAuthDenied: function (authDeniedCb) {
      this.authDeniedCb = authDeniedCb;
    },

    checkAccess: function (roles) {
      var requiredRoles = roles || [],
      that = this;

      return FauxtonAPI.session.fetchUser().then(function (user) {
        return FauxtonAPI.when(that.authHandlerCb(FauxtonAPI.session, requiredRoles));
      });
    }
  });

  FauxtonAPI.auth = new Auth();

  FauxtonAPI.RouteObject = function(options) {
    this._options = options;

    this._configure(options || {});
    this.initialize.apply(this, arguments);
    this.addEvents();
  };

  // Piggy-back on Backbone's self-propagating extend function
  FauxtonAPI.RouteObject.extend = Backbone.Model.extend;

  var routeObjectOptions = ["views", "routes", "events", "roles", "crumbs", "layout", "apiUrl", "establish"];

  _.extend(FauxtonAPI.RouteObject.prototype, Backbone.Events, {
    // Should these be default vals or empty funcs?
    views: {},
    routes: {},
    events: {},
    crumbs: [],
    layout: "with_sidebar",
    apiUrl: null,
    renderedState: false,
    establish: function() {},
    route: function() {},
    roles: [],
    initialize: function() {}
  }, {

    renderWith: function(route, masterLayout, args) {
      var routeObject = this;

      // TODO: Can look at replacing this with events eg beforeRender, afterRender function and events
      this.route.call(this, route, args);

      // Only want to redo the template if its a full render
      if (!this.renderedState) {
        masterLayout.setTemplate(this.layout);
      }

      masterLayout.clearBreadcrumbs();
      var crumbs = this.get('crumbs');

      if (crumbs.length) {
        masterLayout.setBreadcrumbs(new Fauxton.Breadcrumbs({
          crumbs: crumbs
        }));
      }

      FauxtonAPI.when(this.establish()).done(function(resp) {
        _.each(routeObject.getViews(), function(view, selector) {
          if(view.hasRendered()) { return; }

          masterLayout.setView(selector, view);

          FauxtonAPI.when(view.establish()).then(function(resp) {
            masterLayout.renderView(selector);
          }, function(resp) {
            view.establishError = {
              error: true,
              reason: resp
            };
            masterLayout.renderView(selector);
          });

          var hooks = masterLayout.hooks[selector];
          var boundRoute = route;

          _.each(hooks, function(hook){
            if (_.any(hook.routes, function(route){return route == boundRoute;})){
              hook.callback(view);
            }
          });
        });
      });

      if (this.get('apiUrl')) masterLayout.apiBar.update(this.get('apiUrl'));

      // Track that we've done a full initial render
      this.renderedState = true;
    },

    get: function(key) {
      return _.isFunction(this[key]) ? this[key]() : this[key];
    },

    addEvents: function(events) {
      events = events || this.get('events');
      _.each(events, function(method, event) {
        if (!_.isFunction(method) && !_.isFunction(this[method])) {
          throw new Error("Invalid method: "+method);
        }
        method = _.isFunction(method) ? method : this[method];

        this.on(event, method);
      }, this);
    },

    _configure: function(options) {
      _.each(_.intersection(_.keys(options), routeObjectOptions), function(key) {
        this[key] = options[key];
      }, this);
    },

    getView: function(selector) {
      return this.views[selector];
    },

    setView: function(selector, view) {
      this.views[selector] = view;
      return view;
    },

    getViews: function() {
      return this.views;
    },

    getRouteUrls: function () {
      return _.keys(this.get('routes'));
    },

    hasRoute: function (route) {
      if (this.get('routes')[route]) {
        return true;
      }
      return false;
    },

    routeCallback: function (route, args) {
      var routes = this.get('routes'),
      routeObj = routes[route],
      routeCallback;

      if (typeof routeObj === 'object') {
        routeCallback = this[routeObj.route];
      } else {
        routeCallback = this[routeObj];
      }

      routeCallback.apply(this, args);
    },

    getRouteRoles: function (routeUrl) {
      var route = this.get('routes')[routeUrl];

      if ((typeof route === 'object') && route.roles) {
        return route.roles;
      }

      return this.roles;
    }

  });

  app.fauxtonAPI = FauxtonAPI;
  return app.fauxtonAPI;
});
<|endoftext|>


<commit_before>var Quiz = {
    counter: null,

    init: function() {
        this.counter = 0;
        this.bindProblemControls();

        $('#add-problem').click();
        $('.add-answer').click();
    },

    listInit: function() {
        this.bindQuizDelete();
    },

    bindProblemControls: function() {
        $('#add-problem').click(function(event) {
            event.preventDefault();

            Quiz.addNewProblem();
        });

        $('.remove-problem').live('click', function(event) {
            event.preventDefault();

            $(this).parents('.problem-wrapper').remove();
        });

        $('.add-answer').live('click', function(event) {
            event.preventDefault();

            Quiz.addNewAnswer($(this).parents('.answers'));
        });

        $('.remove-answer').live('click', function(event) {
            event.preventDefault();

            $(this).parents('.answer').remove();
        });
    },

    bindQuizDelete: function() {
        $('.delete-quiz').click(function(event) {
            event.preventDefault();

            var $quizRow = $(this).parents('tr');

            if (confirm("Delete this quiz and all of its attempts? This is permanent.")) {
                $.ajax({
                    url: Routing.generate('_quiz_delete'),
                    type: 'POST',
                    data: {'id': $(this).attr('quiz-id')},
                    error: Impetus.errorAlert,
                    success: function(data) {
                        if (data == 'success') {
                            $quizRow.remove();
                        }
                    }
                });
            }
        });
    },

    addNewAnswer: function($context) {
        //var index = $('.remove-answer', $context).length;
        var answer_prototype = $($context).attr('data-prototype');
        var $answer = $(answer_prototype.replace(/\$\$answers\$\$/g, Quiz.counter));
        Quiz.counter++;

        $('.answers-marker', $context).before($answer.clone());
    },

    addNewProblem: function() {
        //var index = $('.remove-problem').length;
        var problem_prototype = $('#problems').attr('data-prototype');
        var $problem = $(problem_prototype.replace(/\$\$questions\$\$/g, Quiz.counter));
        Quiz.counter++;

        $('#problems-marker').before($problem.clone());
    }
}<commit_msg>Stop new quizzes from having a new problem automatically<commit_after>var Quiz = {
    counter: null,

    init: function() {
        this.counter = 0;
        this.bindProblemControls();
    },

    listInit: function() {
        this.bindQuizDelete();
    },

    bindProblemControls: function() {
        $('#add-problem').click(function(event) {
            event.preventDefault();

            Quiz.addNewProblem();
        });

        $('.remove-problem').live('click', function(event) {
            event.preventDefault();

            $(this).parents('.problem-wrapper').remove();
        });

        $('.add-answer').live('click', function(event) {
            event.preventDefault();

            Quiz.addNewAnswer($(this).parents('.answers'));
        });

        $('.remove-answer').live('click', function(event) {
            event.preventDefault();

            $(this).parents('.answer').remove();
        });
    },

    bindQuizDelete: function() {
        $('.delete-quiz').click(function(event) {
            event.preventDefault();

            var $quizRow = $(this).parents('tr');

            if (confirm("Delete this quiz and all of its attempts? This is permanent.")) {
                $.ajax({
                    url: Routing.generate('_quiz_delete'),
                    type: 'POST',
                    data: {'id': $(this).attr('quiz-id')},
                    error: Impetus.errorAlert,
                    success: function(data) {
                        if (data == 'success') {
                            $quizRow.remove();
                        }
                    }
                });
            }
        });
    },

    addNewAnswer: function($context) {
        //var index = $('.remove-answer', $context).length;
        var answer_prototype = $($context).attr('data-prototype');
        var $answer = $(answer_prototype.replace(/\$\$answers\$\$/g, Quiz.counter));
        Quiz.counter++;

        $('.answers-marker', $context).before($answer.clone());
    },

    addNewProblem: function() {
        //var index = $('.remove-problem').length;
        var problem_prototype = $('#problems').attr('data-prototype');
        var $problem = $(problem_prototype.replace(/\$\$questions\$\$/g, Quiz.counter));
        Quiz.counter++;

        $('#problems-marker').before($problem.clone());
    }
}<|endoftext|>


<commit_before>/**
 * Created by dagan on 07/04/2014.
 */
'use strict';
/* global console, XdUtils */
window.xdLocalStorage = window.xdLocalStorage || (function () {
  var MESSAGE_NAMESPACE = 'cross-domain-local-message';
  var options = {
    iframeId: 'cross-domain-iframe',
    iframeUrl: undefined,
    initCallback: function () {}
  };
  var requestId = -1;
  var iframe;
  var requests = {};
  var wasInit = false;
  var iframeReady = false;
  var messageCache = [];

  function applyCallback(data) {
    if (requests[data.id]) {
      requests[data.id](data);
      delete requests[data.id];
    }
  }

  function receiveMessage(event) {
    var data;
    try {
      data = JSON.parse(event.data);
    } catch (err) {
      //not our message, can ignore
    }
    if (data && data.namespace === MESSAGE_NAMESPACE) {
      if (data.id === 'iframe-ready') {
        iframeReady = true;
        options.initCallback();
        messageCache.forEach(function (data) {
            iframe.contentWindow.postMessage(JSON.stringify(data), '*');
          });
        messageCache.length = 0;
      } else {
        applyCallback(data);
      }
    }
  }

  function buildMessage(action, key, value, callback) {
    requestId++;
    requests[requestId] = callback;
    var data = {
      namespace: MESSAGE_NAMESPACE,
      id: requestId,
      action: action,
      key: key,
      value: value
    };
    if (iframeReady) {
      iframe.contentWindow.postMessage(JSON.stringify(data), '*');
    } else {
      messageCache.push(data);
    }
  }
  function init(customOptions) {
    if (wasInit) {
      console.log('xdLocalStorage was already initialized!');
      return;
    }
    wasInit = true;
    options = XdUtils.extend(customOptions, options);
    var temp = document.createDocumentFragment();

    if (window.addEventListener) {
      window.addEventListener('message', receiveMessage, false);
    } else {
      window.attachEvent('onmessage', receiveMessage);
    }

    iframe = temp.ownerDocument.createElement('iframe');
    iframe.id = options.iframeId;
    iframe.src = options.iframeUrl;
    temp.appendChild(iframe);
    document.body.appendChild(temp);
  }

  function isApiReady() {
    if (!wasInit) {
      console.log('You must call xdLocalStorage.init() before using it.');
      return false;
    }
    return true;
  }

  return {
    //callback is optional for cases you use the api before window load.
    init: function (customOptions) {
      if (!customOptions.iframeUrl) {
        throw 'You must specify iframeUrl';
      }
      init(customOptions);
    },
    setItem: function (key, value, callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('set', key, value, callback);
    },

    getItem: function (key, callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('get', key,  null, callback);
    },
    removeItem: function (key, callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('remove', key,  null, callback);
    },
    key: function (index, callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('key', index,  null, callback);
    },
    clear: function (callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('clear', null,  null, callback);
    }
  };
})();<commit_msg>revert(xdLocalStorage): revert merge for message cache. it was not tested and had bugs<commit_after>/**
 * Created by dagan on 07/04/2014.
 */
'use strict';
/* global console, XdUtils */
window.xdLocalStorage = window.xdLocalStorage || (function () {
  var MESSAGE_NAMESPACE = 'cross-domain-local-message';
  var options = {
    iframeId: 'cross-domain-iframe',
    iframeUrl: undefined,
    initCallback: function () {}
  };
  var requestId = -1;
  var iframe;
  var requests = {};
  var wasInit = false;
  var iframeReady = true;

  function applyCallback(data) {
    if (requests[data.id]) {
      requests[data.id](data);
      delete requests[data.id];
    }
  }

  function receiveMessage(event) {
    var data;
    try {
      data = JSON.parse(event.data);
    } catch (err) {
      //not our message, can ignore
    }
    if (data && data.namespace === MESSAGE_NAMESPACE) {
      if (data.id === 'iframe-ready') {
        iframeReady = true;
        options.initCallback();
      } else {
        applyCallback(data);
      }
    }
  }

  function buildMessage(action, key, value, callback) {
    requestId++;
    requests[requestId] = callback;
    var data = {
      namespace: MESSAGE_NAMESPACE,
      id: requestId,
      action: action,
      key: key,
      value: value
    };
    iframe.contentWindow.postMessage(JSON.stringify(data), '*');
  }
  function init(customOptions) {
    if (wasInit) {
      console.log('xdLocalStorage was already initialized!');
      return;
    }
    wasInit = true;
    options = XdUtils.extend(customOptions, options);
    var temp = document.createElement('div');

    if (window.addEventListener) {
      window.addEventListener('message', receiveMessage, false);
    } else {
      window.attachEvent('onmessage', receiveMessage);
    }

    temp.innerHTML = '<iframe id="' + options.iframeId + '" src=' + options.iframeUrl + ' style="display: none;"></iframe>';
    document.body.appendChild(temp);
    iframe = document.getElementById(options.iframeId);
  }

  function isApiReady() {
    if (!wasInit) {
      console.log('You must call xdLocalStorage.init() before using it.');
      return false;
    }
    if (!iframeReady) {
      console.log('You must wait for iframe ready message before using the api.');
      return false;
    }
    return true;
  }

  return {
    //callback is optional for cases you use the api before window load.
    init: function (customOptions) {
      if (!customOptions.iframeUrl) {
        throw 'You must specify iframeUrl';
      }
      if (document.readyState === 'complete') {
        init(customOptions);
      } else {
        window.onload = function () {
          init(customOptions);
        };
      }
    },
    setItem: function (key, value, callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('set', key, value, callback);
    },

    getItem: function (key, callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('get', key,  null, callback);
    },
    removeItem: function (key, callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('remove', key,  null, callback);
    },
    key: function (index, callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('key', index,  null, callback);
    },
    clear: function (callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('clear', null,  null, callback);
    }
  };
})();<|endoftext|>


<commit_before>({
	removePrefixListSettings : function(settings, namespacePrefix) {
		if(namespacePrefix && namespacePrefix.length > 0) {
			//We need to end up with an array of objects, because the settings param is an array of objects
    		var settings_no_prefix = []; //create array
    		//Remove package prefix from each custom field
    		for(var key in settings) { //Iterate over each row - key is just a numeric index here
    			var obj = {}; //create object
    			for(var key2 in settings[key]) { //Iterate over each field in each row - key2 is the actual field name
    				if(key2.endsWith('__c')) {
	    				var key2_no_prefix = key2.replace(namespacePrefix, '');
	    				obj[key2_no_prefix] = settings[key][key2];
	    			} else {
	    				obj[key2] = settings[key][key2];
	    			}
    			}
    			settings_no_prefix.push(obj);
    		}
    		return settings_no_prefix;
		} else {
			return settings;
		}
	},

	removePrefixHierarchySettings : function(settings, namespacePrefix) {
		if(namespacePrefix && namespacePrefix.length > 0) {
    		var settings_no_prefix = {};
    		//Remove package prefix from each custom field
    		for(var key in settings) { //Iterate over each row
    			if(key.endsWith('__c')) {
    				var key_no_prefix = key.replace(namespacePrefix, '');
	    			settings_no_prefix[key_no_prefix] = settings[key];
    			} else {
    				settings_no_prefix[key] = settings[key];
    			}
    		}
    		return settings_no_prefix;
		} else {
			return settings;
		}
	},

	addPrefixHierarchySettings : function(settings, namespacePrefix) {
		if(namespacePrefix && namespacePrefix.length > 0) {
    		var settings_w_prefix = {};
    		//Remove package prefix from each custom field
    		for(var key in settings) { //Iterate over each row
    			if(key.endsWith('__c')) {
    				var key_w_prefix = namespacePrefix + key;
	    			settings_w_prefix[key_w_prefix] = settings[key];
    			} else {
    				settings_w_prefix[key] = settings[key];
    			}
    		}
    		return settings_w_prefix;
		} else {
			return settings;
		}
	},

	//Not used right now! It seems like you don't need to add the prefix for saving list settings.
	addPrefixListSettings : function(settings, namespacePrefix) {
		if(namespacePrefix && namespacePrefix.length > 0) {
			var settings_w_prefix = {};
			//Add package prefix to each custom field
			for(var key in settings) {
				if(key.endsWith('__c')) {
					var key_w_prefix = namespacePrefix + key;
	    			settings_w_prefix[key_w_prefix] = settings[key];
				} else {
					settings_w_prefix[key] = settings[key];
				}
			}
			return settings_w_prefix;
		} else {
			return settings;
		}
	},

	displayError : function(response) {
		var errors = response.getError();
		if (errors && errors[0].pageErrors[0] && errors[0].pageErrors[0].message) {
			$A.error("Error message: " + errors[0].pageErrors[0].message);
		} else {
			$A.error("Unknown error");
		}
	}
})<commit_msg>Improving error notifications.<commit_after>({
	removePrefixListSettings : function(settings, namespacePrefix) {
		if(namespacePrefix && namespacePrefix.length > 0) {
			//We need to end up with an array of objects, because the settings param is an array of objects
    		var settings_no_prefix = []; //create array
    		//Remove package prefix from each custom field
    		for(var key in settings) { //Iterate over each row - key is just a numeric index here
    			var obj = {}; //create object
    			for(var key2 in settings[key]) { //Iterate over each field in each row - key2 is the actual field name
    				if(key2.endsWith('__c')) {
	    				var key2_no_prefix = key2.replace(namespacePrefix, '');
	    				obj[key2_no_prefix] = settings[key][key2];
	    			} else {
	    				obj[key2] = settings[key][key2];
	    			}
    			}
    			settings_no_prefix.push(obj);
    		}
    		return settings_no_prefix;
		} else {
			return settings;
		}
	},

	removePrefixHierarchySettings : function(settings, namespacePrefix) {
		if(namespacePrefix && namespacePrefix.length > 0) {
    		var settings_no_prefix = {};
    		//Remove package prefix from each custom field
    		for(var key in settings) { //Iterate over each row
    			if(key.endsWith('__c')) {
    				var key_no_prefix = key.replace(namespacePrefix, '');
	    			settings_no_prefix[key_no_prefix] = settings[key];
    			} else {
    				settings_no_prefix[key] = settings[key];
    			}
    		}
    		return settings_no_prefix;
		} else {
			return settings;
		}
	},

	addPrefixHierarchySettings : function(settings, namespacePrefix) {
		if(namespacePrefix && namespacePrefix.length > 0) {
    		var settings_w_prefix = {};
    		//Remove package prefix from each custom field
    		for(var key in settings) { //Iterate over each row
    			if(key.endsWith('__c')) {
    				var key_w_prefix = namespacePrefix + key;
	    			settings_w_prefix[key_w_prefix] = settings[key];
    			} else {
    				settings_w_prefix[key] = settings[key];
    			}
    		}
    		return settings_w_prefix;
		} else {
			return settings;
		}
	},

	//Not used right now! It seems like you don't need to add the prefix for saving list settings.
	addPrefixListSettings : function(settings, namespacePrefix) {
		if(namespacePrefix && namespacePrefix.length > 0) {
			var settings_w_prefix = {};
			//Add package prefix to each custom field
			for(var key in settings) {
				if(key.endsWith('__c')) {
					var key_w_prefix = namespacePrefix + key;
	    			settings_w_prefix[key_w_prefix] = settings[key];
				} else {
					settings_w_prefix[key] = settings[key];
				}
			}
			return settings_w_prefix;
		} else {
			return settings;
		}
	},

	displayError : function(response) {
		var errors = response.getError();
		if (errors && errors[0].pageErrors[0] && errors[0].pageErrors[0].message) {
			$A.error("Error message: " + errors[0].pageErrors[0].message);
		} else if(errors && errors[0].fieldErrors && errors[0].fieldErrors.Name[0] && errors[0].fieldErrors.Name[0].message) {
			$A.error("Error message: " + errors[0].fieldErrors[0].Name[0].message);
		} else {
			$A.error("Unknown error");
		}
	}
})<|endoftext|>


<commit_before>/**
 * A general serial port helper.
 * @module io/serial
 * @author Sören Gade
 *
 * @requires serialport
 * */

var serialport = require('serialport');

/**
 * A callback that is called with two parameters.
 * @callback ErrorResultCallback
 * @param {Exception} err - Is an error object or null.
 * @param {Object} object - The resulting data.
 * */
/**
 * Lists all serial port devices found on the device.
 * @param {ErrorResultCallback} callback - A callback that is called upon finish or error.
 * */
exports.list = function(callback) {
  serialport.list(callback);
};
<commit_msg>Fixed doc.<commit_after>/**
 * A general serial port helper.
 * @module io/serial
 * @author Sören Gade
 *
 * @requires serialport
 * */

var serialport = require('serialport');

/**
 * A callback that is called with two parameters.
 * @callback ErrorResultCallback
 * @param {Exception} err - Is an error object or null.
 * @param {Object} object - The resulting data.
 * */
/**
 * Lists all serial ports found on the device.
 * @param {ErrorResultCallback} callback - A callback that is called upon finish or error.
 * */
exports.list = function(callback) {
  serialport.list(callback);
};
<|endoftext|>


<commit_before>module.exports = function() {

    // this.clientServer = function() { return "localhost:3000" }
    // this.apiServer = function() { return "localhost:2300"}

    var configurations = {

        "localhost": {

            "clientServer": "localhost:3000",
            "apiServer": "localhost:2300",
            "serverCommand": "runh",
            "remarks": "Image upload works on host machine"
        },

        "jxxmbp.local": {

            "clientServer": "jxxmbp.local:3000",
            "apiServer": "jxxmbp.local:2300",
            "serverCommand": "runh",
            "remarks": "Image upload works on host & local machines"
        },

        "heroku-local": {

            "clientServer": "jxxmbp.local:3000",
            "apiServer": "jxxmbp.local:5000",
            "serverCommand": "heroku local",
            "remarks": "Image upload works on host & local machines"
        },

        "heroku&local": {

            "clientServer": "jxxmbp.local:3000",
            "apiServer": "sleepy-tundra-14212.herokuapp.com",
            "serverCommand": "-- api server runs remotely",
            "remarks": "Image upload fails with internal server error, Unexpected token I in JSON at positon 0"
        }
    }

    var configuration = "jxxmbp.local"

    this.configuration = function() { return configuration }
    this.clientServer = function() { return configurations[configuration]["clientServer"] }
    this.apiServer = function() { return configurations[configuration]["apiServer"] }
    this.serverCommand = function() { return configurations[configuration]["serverCommand"] }
    this.remarks = function() { return configurations[configuration]["remarks"] }

    this.defaultDocumentID = function() { return 11 }

}<commit_msg>Set configuration from both client and api server to be on heroku<commit_after>module.exports = function() {

    // this.clientServer = function() { return "localhost:3000" }
    // this.apiServer = function() { return "localhost:2300"}

    var configurations = {

        "localhost": {

            "clientServer": "localhost:3000",
            "apiServer": "localhost:2300",
            "serverCommand": "runh",
            "remarks": "Image upload works on host machine"
        },

        "jxxmbp.local": {

            "clientServer": "jxxmbp.local:3000",
            "apiServer": "jxxmbp.local:2300",
            "serverCommand": "runh",
            "remarks": "Image upload works on host & local machines"
        },

        "heroku-local": {

            "clientServer": "jxxmbp.local:3000",
            "apiServer": "jxxmbp.local:5000",
            "serverCommand": "heroku local",
            "remarks": "Image upload works on host & local machines"
        },

        "heroku&local": {

            "clientServer": "jxxmbp.local:3000",
            "apiServer": "sleepy-tundra-14212.herokuapp.com",
            "serverCommand": "-- api server runs remotely",
            "remarks": "Image upload fails with internal server error, Unexpected token I in JSON at positon 0"
        },

        "heroku&heroku": {

            "clientServer": "salty-savannah-99428.herokuapp.com",
            "apiServer": "sleepy-tundra-14212.herokuapp.com",
            "serverCommand": "-- api server runs remotely",
            "remarks": "Image upload fails with internal server error, Unexpected token I in JSON at positon 0"
        }
    }

    var configuration = "heroku&heroku"

    this.configuration = function() { return configuration }
    this.clientServer = function() { return configurations[configuration]["clientServer"] }
    this.apiServer = function() { return configurations[configuration]["apiServer"] }
    this.serverCommand = function() { return configurations[configuration]["serverCommand"] }
    this.remarks = function() { return configurations[configuration]["remarks"] }

    this.defaultDocumentID = function() { return 11 }

}<|endoftext|>