text:
(function () {

var global = this;
/**
 * boxxer object
 * @type {Object}
 */
var exports = {};

/**
 * boxxer API object
 * @type {Object}
 * @namespace
 */
var api = Object.create(exports);

/**
 * old boxxer
 * @type {Object}
 */
var _boxxer = global.boxxer;

/**
 * renderer element
 * @type {HTMLElement}
 */
var renderer = document.createElement("div");
//hide the renderer element to prevent unnecessary reflows
renderer.style.display = "none";

if (_boxxer) {
    exports._boxxer = _boxxer;
}

//export API object
global.boxxer = api;

/**
 * descendant class level constructor
 * @constructor Surrogate
 */
function Surrogate() {}

/**
 * determines whether boxxer should be built in debug mode
 * @return {Boolean}
 */
function debugMode() {
    return (global.boxxer_debug === true);
}

/**
 * removes an element from its parent element
 * @param element {HTMLElement}
 */
function removeElement(element) {
    var parent = element.parentNode;

    if (parent) {
        parent.removeChild(element);
    }
}

/**
 * returns the browser specific target Element in an Event object
 * @param evt {Event}
 * @returns {Object}
 */
function getEventTarget(evt) {
    return (evt.target || evt.srcElement);
}

/**
 * returns the document body
 * @private
 * @static
 * @return {HTMLElement}
 */
function getBody() {
    return document.body;
}

/**
 * initializes a renderer element by appending it to the DOM and hiding it
 * @param eElement {HTMLElement|undefined} parent to append the renderer element to
 */
function init(eElement) {
    //appending invisible renderer element
    (eElement || getBody()).appendChild(renderer);
}

/**
 * returns the renderer element
 * @returns {HTMLElement}
 */
function getRenderer() {
    return renderer;
}

/**
 * extender - inheritance resolver
 * @param subClass {Function} sub class - surprised on this?
 * @param superClass {Function} super class - the Force is strong with this one...
 */
function inherit(subClass, superClass) {
    var TemporarySuperClass = function () {};

    if (debugMode()) {
        //I know, but I still prefer the
        //clean visual prototype chain
        //with proper class names instead
        //of "__proto__ > haku.nama.tata"
        eval("TemporarySuperClass = function " + subClass.name + "() {};");
    }

    TemporarySuperClass.prototype = superClass.prototype;

    subClass.prototype = new TemporarySuperClass();
    subClass.prototype.constructor = subClass;
}

/**
 * mixes two classes by their prototype
 * @param mainClass {Function} class getting partial stuff
 * @param mixClass {Function} partial class implementation
 */
function mix(mainClass, mixClass) {
    var i;

    for (i in mixClass.prototype) {
        if (mixClass.prototype.hasOwnProperty(i)) {
            mainClass.prototype[i] = mixClass.prototype[i];
        }
    }
}

//expose registering method
exports.Surrogate = Surrogate;

//expose core utility functions
exports.mix = mix;
exports.inherit = inherit;
exports.debugMode = debugMode;

//expose utility functions
exports.utils = {
    getBody : getBody,
    getRenderer : getRenderer,
    getEventTarget : getEventTarget,
    removeElement: removeElement
};

//expose initialize function
exports.init = init;
exports.Async = Async;

/**
 * provides save mixin method for Box instances for asynchronous state saving
 * @constructor Async
 */
function Async() {}

/**
 * method gets merged to the implementor class
 * @returns {*}
 */
Async.prototype.save = function (url, callback, format, method) {
    return Async.saveBox(this, url, method, callback, format);
};

/**
 * serializes and saves the given Box instance
 * @param box {boxxer.Box}
 * @param url {String}
 * @param [method] {String} GET/POST
 * @param [callback] {Function}
 * @param [format] {String}
 */
Async.saveBox = function (box, url, method, callback, format) {
    if (!format) {
        format = Serializer.JSON;
    }

    new Connection(box, url, method, format, callback).save();
};

/**
 * PUT request
 * @type {string}
 */
Async.POST = "PUT";

/**
 * DELETE request
 * @type {string}
 */
Async.POST = "DELETE";

/**
 * POST request
 * @type {string}
 */
Async.POST = "POST";

/**
 * GET request
 * @type {string}
 */
Async.GET = "GET";

exports.Connection = Connection;

/**
 * @description Connection class is responsible to handle all asynchronous Box persistence
 * @param url {String}
 * @param params {Object}
 * @constructor Connection
 */
function Connection(url, params) {
    this._url = url;
    this._data = params.data || "";
    this._callback = params.callback;
    this._request = new XMLHttpRequest(); //IE7+
}

/**
 * method will be invoked on each state change on the request object
 */
Connection.prototype.onStateChange = function () {
    var request = this._request;
    var args;

    if (typeof this._callback === "function") {
        if (request.readyState === 4 && request.status === 200) {
            args = Array.prototype.slice(arguments);
            args.unshift(request, request.responseText);

            this._callback.apply(null, args);
        }
    }
};

/**
 * Send a "POST" request
 */
Connection.prototype.save = function() {
    this._request.onreadystatechange = this.onStateChange.bind(this);
    this._request.open(Connection.POST, this._url, true);
    this._request.send(this._data);
};
/**
 * Send a "PUT" request
 */
Connection.prototype.create = function() {
    this._request.onreadystatechange = this.onStateChange.bind(this);
    this._request.open(Connection.PUT, this._url, true);
    this._request.send(this._data);
};

/**
 * Send a DELETE request
 */
Connection.prototype.remove = function(){
    this._request.onreadystatechange = this.onStateChange.bind(this);
    this._request.open(Connection.DELETE, this._url, true);
    this._request.send();
};

/**
 * Send a GET request
 */
Connection.prototype.get = function(){
    this._request.onreadystatechange = this.onStateChange.bind(this);
    this._request.open(Connection.GET, this._url, true);
    this._request.send();
};

/**
 * PUT request
 * @type {string}
 */
Connection.PUT = "PUT";

/**
 * DELETE request
 * @type {string}
 */
Connection.DELETE = "DELETE";

/**
 * POST request
 * @type {string}
 */
Connection.POST = "POST";

/**
 * GET request
 * @type {string}
 */
Connection.GET = "GET";

exports.Component = Component;

/**
 * @interface
 * @class
 * This interface must be implemented by a presentation-level class.
 * A presentation-level class represents something that occupies physical space in the page
 * container, such as the content of a panel or a dialog box. Component extends the
 * {@link Lifecycle} interface which defines the life cycle events that may be raised by the container
 * in response to the user's interaction with it. The Component is automatically registered
 * with its container so that it receives these life cycle event callbacks.
 *
 *
Each implementation of a Component represents a different Component type,
 * for example a Grid or a Trade Panel.

 *
 *
Each subclass of Component must have an createFromSerializedState method
 * which is responsible for constructing new instances of the Component.
 *
 *
The windowing environment, which provides the container within which the component exists,
 * may only use a subset of the Component interface. A component therefore should be
 * implemented so that it will work even if the (mandatory) methods {@link #getElement} and
 * {@link LifeCycle#onOpen} are the only methods the windowing environment will invoke.

 *
 *
The windowing environment determines whether the event methods are called immediately after
 * or immediately before the event they refer to.

 *
 *
Component instances that have been configured via XML or saved as part of a
 * layout are instantiated by the ComponentFactory. As such a
 * Component must be registered with the using the factory's
 * ComponentFactory.registerComponent method, passing
 * in the name of the root XML tag that represents the component and a suitable static factory
 * method can instantiate it.
 * @constructor
 *
 * @implements LifeCycle
 * @component
 */
function Component() {}

/**
 * Returns a reference to the container that is hosting this component. If no container has been
 * set then this will return undefined.
 *
 * @deprecated
 * @return {Box} The box hosting this component.
 */
Component.prototype.getContainer = function () {
    return this.container;
};

/**
 * Provides a reference to the container that will be hosting this component.
 *
 * @deprecated
 * @see #setFrame
 * @param {box} box The container hosting this component.
 */
Component.prototype.setContainer = function (box) {
    this.container = box;
};

/**
 * Just leaving it for now just in case but not sure we need it
 * @deprecated
 */
Component.prototype.setFrame = Component.prototype.setContainer;

/**
 * Gets a guaranteed ID for this component instance.
 * @type String
 * @return A unique ID
 * @throws {Error} if this method is not implemented by the subclass.
 */
// TODO do we need this as boxes have an ID? I guess so but need to look into it
Component.prototype.getUniqueComponentId = function () {
    throw new Error("Component.getUniqueComponentId() has not been implemented.");
};

/**
 * Invoked when the windowing environment needs to display this component. It returns the HTML
 * element that must be added to the DOM to represent this component. getElement()
 * is invoked before any of the other Component interface methods.
 *
 *
This method is compulsory, and must be implemented.

 *
 *
It should be designed execute quickly, as the windowing environment may freeze
 * until it has returned.

 *
 * @type HtmlElement
 * @return The root HtmlElement used to display this component on a web page.
 * Must not be null or undefined.
 * @throws {Error} if this method is not implemented by the subclass.
 */
Component.prototype.getElement = function () {
    throw new Error("Component.getElement() has not been implemented.");
};

/**
 * Invoked when the windowing environment needs to save the state of this component. It returns an
 * XML string or JSON object representation of the state.
 *
 *
This method is compulsory, and must be implemented.

 *
 *
Example:

 *
 *

 * mybank.MyComponent = function()
 * {
 *	this.m_sSubject = null;
 * };
 * caplin.implement(mybank.MyComponent, Component);
 *
 * mybank.MyComponent.setSubject = function(sSubject)
 * {
 *	this.m_sSubject = sSubject;
 * };
 *
 * // other Component methods ...
 *
 * mybank.MyComponent.getSerializedState = function()
 * {
 *	return "<myComponent subject=\"" + this.m_sSubject + "\" />";
 * };
 *

 *
 * @type String
 * @return An XML string representation of the state of this component.
 * Must not be null or undefined.
 * @throws {Error} if this method is not implemented by the subclass.
 */
// TODO update jsdoc with JSON example instead of XML
Component.prototype.getSerializedState = function () {
    throw new Error("Component.getSerializedState() has not been implemented.");
};

/**
 * Invoked so the container can determine whether the component is currently permissioned for use.
 *
 * @return The set of permissioning information that can be used to query
 * {@link caplin.services.security.PermissionService#canUserPerformAction}.
 * @type caplin.services.security.PermissionKey
 */
// TODO Something with this...
Component.prototype.getPermissionKey = function () {};

exports.LifeCycle = LifeCycle;

/**
 * @beta
 * @class
 *
Component life cycle events are emitted by the box instances. Overriding any of the methods
 * in this listener interface is optional, but doing so will enable you to react to the related
 * event.

 *
 * @constructor
 * @interface
 */
function LifeCycle() {}

/**
 * Invoked when the frame is first displayed. It will only ever be called once when the box instance is rendered to the
 * document so that dimensions can be calculated.
 *
 * @param box {Box}
 */
LifeCycle.prototype.onOpen = function(box) {};

/**
 * Invoked when the frame containing this component is closed.
 *
 *
This method should be used to clean up any resources the component currently has open,
 * including subscriptions and any other listeners that may have been registered. Once
 * onClose() has been called no further methods will be called for this
 * component.

 *
 * @param box {Box}
 */
LifeCycle.prototype.onClose = function(box) {};

/**
 * Invoked when a box that has been hidden (see {@link #onHide}) is now back in view. It
 * should restore any resources that were stopped or suspended by onHide().
 *
 *
Note that this method is not called when the component within the frame is first
 * displayed (see {@link #onOpen}).

 *
 * @param box {Box}
 */
LifeCycle.prototype.onShow = function(box) {};

/**
 * Invoked when a frame is no longer in view. It should stop or suspend any resources that may
 * be processor intensive, such as subscriptions, so they are not active whilst the
 * frame is hidden.
 *
 * @see #onShow
 *
 * @param box {Box}
 */
LifeCycle.prototype.onHide = function(box) {};

/**
 * Invoked when the frame has been minimized.
 *
 * @see #onRestore
 *
 * @param box {Box}
 */
LifeCycle.prototype.onMinimize = function(box) {};

/**
 * Invoked when the frame has been maximized.
 *
 * @see #onRestore
 *
 * @param box {Box}
 */
LifeCycle.prototype.onMaximize = function(box) {};

/**
 * Invoked when the frame has been restored from a minimized or maximized state.
 *
 * @see #onMinimize
 * @see #onMaximize
 *
 * @param box {Box}
 */
LifeCycle.prototype.onRestore = function(box) {};

/**
 * Invoked when the dimensions of the frame change.
 *
 * @param box {Box}
 */
LifeCycle.prototype.onResize = function(box) {};

/**
 * Invoked when the frame becomes the active or focused frame within the page.
 *
 * @param box {Box}
 */
// TODO this is not ideal as API onFocus would be better but we can create an alias
LifeCycle.prototype.onActivate = function(box) {};

/**
 * Invoked when the frame ceases to be the active or focused frame within the page.
 *
 * @param box {Box}
 */
// TODO this is not ideal as API onBlur would be better but we can create an alias
LifeCycle.prototype.onDeactivate = function(box) {};

/**
 * Invoked when the frame ceases to be the active or focused frame within the page.
 *
 * @param box {Box}
 */
LifeCycle.prototype.onReflow = function(box) {};
exports.Decorator = Decorator;

/**
 * @constructor Decorator
 */
function Decorator() {}

/**
 * returns a predefined template
 * @returns {HTMLElement}
 */
Decorator.prototype.getTemplate = function () {
    var element = document.createElement(this.tagName || 'div');
    if (this.className) {
        element.className = this.className;
    }
    return element;
};

/**
 * registry for every decorator
 * @static
 * @type {{}}
 */
Decorator.registry = {};

/**
 * determines whether a decorator has already been registered
 * @param decoratorName {String} name of the decorator
 * @returns {Boolean}
 */
Decorator.isRegistered = function (decoratorName) {
    return Decorator.registry.hasOwnProperty(decoratorName);
};

/**
 * returns an instance of the requested decorator
 * @param decoratorName {String} The name reference for the decorator
 * @param box {Box} box instance to apply decorator too
 * @returns {Decorator}
 */
Decorator.get = function (decoratorName, box) {
    var decorator = Decorator.extend(Decorator.registry[decoratorName]);
    decorator.box = box;
    decorator.template = decorator.getTemplate();

    if (decorator.events) {
        Decorator.setupEvents(decorator);
    }

    if (typeof decorator.initialize === 'function') {
        decorator.initialize();
    }
    return decorator;
};

/**
 * Handle events binding on decorators using the events property map
 * @param decorator {Decorator}
 */
Decorator.setupEvents = function(decorator) {
    var events = decorator.events;
    var template = decorator.template;
    var event;

    for(event in events) {
        new DOMEvent(template.getElement()).on(event, function(domEvent) {
            Decorator.handleEvent(domEvent, decorator);
        });
    }
};

/**
 * Handle event fired in a decorator and trigger methods based on the events map
 * @param domEvent {DOMEvent}
 * @param decorator {Decorator}
 */
Decorator.handleEvent = function(domEvent, decorator) {

    var queries = decorator.events[domEvent.type];
    var target = new ElementWrapper(domEvent.target);
    var query;

    for (query in queries) {
        // TODO we want to support all queries ideally not just single class or id
        // Probably need to build a map of target in setup for faster processing when events are fired
        if (target.hasClass(query.substring(1, query.length)) || target.id === query.substring(1, query.length)) {
            decorator[queries[query]].apply(decorator, [domEvent]);
        }
    }

};

/**
 * creates a new decorator instance to decorate
 * @param prototype
 * @returns {Decorator}
 */
Decorator.extend = function (prototype) {
    var decorator = new Decorator();
    var property;

    for (property in prototype) {
        if (prototype.hasOwnProperty(property)) {
            decorator[property] = prototype[property];
        }
    }

    return decorator;
};

/**
 * creates and registers a new decorator
 * @param name {String} name of the Decorator
 * @param prototype {Object} map containing the applied functionality
 * @returns {Decorator|undefined}
 */
Decorator.register = function (name, prototype) {
    Decorator.registry[name] = prototype;
};

exports.createDecorator = Decorator.register;

exports.BoxEvent = BoxEvent;

/**
 * BoxEvent subscription class
 * @param eventType {String} the event type which the event is subscribed
 * @param fallback {Function} callback to execute
 * @param context {Object} custom context
 * @constructor BoxEvent
 */
function BoxEvent(eventType, fallback, context) {
    this._eventType = eventType;
    this._callback = fallback;
    this._context = context;
    this._muted = false;
    this._id = ('event_' + BoxEvent._id++);
}

/**
 * executes the Event instance if the object s not muted
 */
BoxEvent.prototype.execute = function () {
    if (!this.isMuted()) {
        var args = Array.prototype.slice.call(arguments);
        args.unshift(this.getEventType());

        this._callback.apply(this._context, args);
    }
};

/**
 * returns the id of the Event
 * @return {Number}
 */
BoxEvent.prototype.getId = function () {
    return this._id;
};

/**
 * returns the type which the event is registered to
 * @return {String}
 */
BoxEvent.prototype.getEventType = function () {
    return this._eventType;
};

/**
 * mutes the Event - does not let the Event to execute
 */
BoxEvent.prototype.mute = function () {
    this._muted = true;
};

/**
 * unmutes the Event
 */
BoxEvent.prototype.unmute = function () {
    this._muted = false;
};

/**
 * determines whether the Event is muted or not
 * @return {Boolean}
 */
BoxEvent.prototype.isMuted = function () {
    return this._muted;
};

/**
 * @private
 * @static
 * @type {Number}
 */
BoxEvent._id = 0;

exports.DOMEvent = DOMEvent;

/**
 * class to simplify DOm event binding
 * @param element {HTMLElement}
 * @constructor
 */
function DOMEvent(element) {
    this._element = element;
    this._callback = {};
    return this;
}

/**
 * Bind an event
 * @param eventType
 * @param callback
 */
DOMEvent.prototype.on = function(eventType, callback) {
    this._callback[eventType] = callback;
    this._eventType = eventType;
    DOMEvent.addListener(this._element, this._eventType, this._callback[eventType]);
    return this;
};

/**
 * Unbind an event
 * @param eventType
 * @returns {*}
 */
DOMEvent.prototype.off = function(eventType) {
    if (this._callback) {
        DOMEvent.removeListener(this._element, this._eventType, this._callback[eventType]);
    }
    return this;
};

DOMEvent._div = document.createElement('div');

/**
 * static bind event method
 * @param element
 * @param eventType
 * @param callback
 */
DOMEvent.addListener = function(element, eventType, callback) {
    element.addEventListener(eventType, callback, false);
};

/**
 * static unbind event method
 * @param element
 * @param eventType
 * @param callback
 */
DOMEvent.removeListener = function(element, eventType, callback) {
    element.removeEventListener(eventType, callback, false);
};
exports.EventEmitter = EventEmitter;

/**
 * EventEmitter instances are able to register and emit events
 * @constructor EventEmitter
 */
function EventEmitter() {
    /**
     * map to store event types and Events by their ids
     * @private
     * @type {Object}
     */
    this._eventTypes = {};

    /**
     * map to store muted event types as keys
     * @private
     * @type {Object}
     */
    this._mutedTypes = {};
}

/**
 * @private
 * registers an event type
 * @param eventType {String}
 * @return {Object}
 */
EventEmitter.prototype._createEventType = function (eventType) {
    if (!this._eventTypes.hasOwnProperty(eventType)) {
        this._eventTypes[eventType] = {};
    }

    return this._eventTypes[eventType];
};

/**
 * registers an Event
 * @param eventType {String} event type
 * @param callback {Function} callback method
 * @param context {Object} custom context
 * @return {BoxEvent}
 */
EventEmitter.prototype.on = function (eventType, callback, context) {
    var event = new BoxEvent(eventType, callback, (context || this));

    this._createEventType(eventType)[event.getId()] = event;

    return event;
};

/**
 * un-registers the Event
 * @param event {BoxEvent} Event instance
 */
EventEmitter.prototype.off = function (event) {
    if (!(event instanceof BoxEvent)) {
        throw new TypeError("Cannot un-register a non-Event type object...");
    }

    delete this._eventTypes[event.getEventType()][event.getId()];
};

/**
 * mutes an event type
 * @param eventType {String} event type
 */
EventEmitter.prototype.mute = function (eventType) {
    this._mutedTypes[eventType] = true;
};

/**
 * mutes an event type
 * @param eventType {String} event type
 */
EventEmitter.prototype.unmute = function (eventType) {
    delete this._mutedTypes[eventType];
};

/**
 * determines whether an event type is muted or not
 * @param eventType {String} event type
 */
EventEmitter.prototype.isMuted = function (eventType) {
    return this._mutedTypes.hasOwnProperty(eventType);
};

/**
 * executes all registered Events for an even type
 */
EventEmitter.prototype.emit = function () {
    var args = Array.prototype.slice.call(arguments),
        eventType = args.shift(),
        eventTypes = this._eventTypes[eventType],
        event,
        id;

    if (!this.isMuted(eventType)) {
        for (id in eventTypes) {
            if (eventTypes.hasOwnProperty(id)) {
                event = eventTypes[id];
                event.execute.apply(event, args);
            }
        }
    }
};

/**
 * Fired when the box is rendered
 * @static
 * @type {String}
 */
EventEmitter.ON_RENDER = "render";

/**
 * Fired when the box is updated
 * @static
 * @type {String}
 */
EventEmitter.ON_UPDATE = "update";

/**
 * Fired when the box is shown
 * @static
 * @type {String}
 */
EventEmitter.ON_SHOW = "show";

/**
 * Fire when the box is hidden
 * @static
 * @type {String}
 */
EventEmitter.ON_HIDE = "hide";

/**
 * Fired when the box is resized
 * @static
 * @type {String}
 */
EventEmitter.ON_RESIZE = "resize";

/**
 * Fired when the box flow is changed
 * @static
 * @type {String}
 */
EventEmitter.ON_REFLOW = "flow";

/**
 * Fired when the box gain focus
 * @static
 * @type {String}
 */
EventEmitter.ON_FOCUS = "focus";

/**
 * Fired when the box loses focus
 * @static
 * @type {String}
 */
EventEmitter.ON_BLUR = "blur";

/**
 * Fired when the box is restored
 * @static
 * @type {String}
 */
EventEmitter.ON_RESTORE = "restore";

/**
 * Fired when the box is minimized
 * @static
 * @type {String}
 */
EventEmitter.ON_MINIMIZE = "minimize";

/**
 * Fired when the box is maximized
 * @static
 * @type {String}
 */
EventEmitter.ON_MAXIMIZE = "maximize";

exports.Layout = Layout;

/**
 * Abstract class that extend box instance and provide layout persistence
 * @constructor Layout
 */
function Layout() {}

/**
 * Return the path for the layout
 * @returns {*}
 */
Layout.prototype.getLayoutPath = function() {
    return this.getName() || this.getId();
};

/**
 * Retrieve a layout from the back-end
 */
Layout.prototype.getLayout = function() {
    var callback = function(rawData) {
        var data = JSON.parse(rawData.responseText);
        var layout = data.layout;
        var box = Serializer.deserialize(layout);

        this.addBox(box);
    }.bind(this);

    new Connection(Layout.URL + "/" + this.getLayoutPath(), {
        callback: callback
    }).get();
};

/**
 * Save a layout in the back-end
 * @param name
 */
Layout.prototype.saveLayout = function(name) {
    var layout = this.serialize(Serializer.JSON, name || null);

    new Connection(Layout.URL + "/" + this.getLayoutPath(), {
        data: layout
    }).save();
};

/**
 * Delete a layout from the back-end
 */
Layout.prototype.deleteLayout = function() {
    new Connection(Layout.URL + this.getLayoutPath()).remove();
};

/**
 * Path to the layouts API
 * @type {string}
 */
Layout.URL = window.location.href + "/layout";

exports.Manager = Manager;

/**
 * Seperate class which aim to facilitate managing multiple layouts
 * @constructor
 */
function Manager() {}

exports.Adjustable = Adjustable;

/**
 * Adjustable mixin class provides the required dimension handler methods
 * @name Adjustable
 * @constructor
 */
function Adjustable() {}

/**
 * @returns {boxxer.render.Dimension}
 */
Adjustable.prototype.getWidth = function () {
    return this.width;
};

/**
 * @returns {boxxer.render.Dimension}
 */
Adjustable.prototype.getHeight = function () {
    return this.height;
};

/**
 * sets the width
 * @param width {String|Number}
 */
Adjustable.prototype.setWidth = function (width) {
    this._setElementWidth(parseInt(width));
};

/**
 * sets the height
 * @param height {String|Number}
 */
Adjustable.prototype.setHeight = function (height) {
    this._setElementHeight(parseInt(height));
};

/**
 * sets both width and height
 * @param width {String|Number}
 * @param height {String|Number}
 */
Adjustable.prototype.setDimensions = function (width, height) {
    this.setWidth(width);
    this.setHeight(height);
};

// TODO Move this file to the component directory
exports.BoxComponent = BoxComponent;

/**
 * @name BoxComponent
 * Component adapter class to provide ComponentLifeCycleEvents for the Component inside the Box
 * @param component {Component|undefined}
 * @constructor BoxComponent
 */
function BoxComponent(component) {
    /**
     * @type {Component|undefined}
     */
    this.component = component;
}

/**
 * sets the component on the Box instance
 * @param component {Component}
 * @returns {Box}
 */
BoxComponent.prototype.setComponent = function (component) {

    var element =  this.getElement();

    if (component) {
        this.component = component;
        element.appendChild(component.getElement());
        this.component.setContainer(element);
    }

    return this;
};

/**
 * returns the Component
 * @returns {Component}
 */
BoxComponent.prototype.getComponent = function () {
    return this.component;
};

/**
 * invokes onOpen or onResize for the Component inside the Box
 * instance depending whether the Box has been rendered or not.
 * @param box {Box}
 * @returns {Box}
 */
BoxComponent.render = function (box) {
    return BoxComponent.invoke(!box.isRendered ? "onOpen" : "onResize", box);
};

/**
 * Invokes a onEvent method on a component if it is present
 * @param methodName {String} Method name to invoke on the component
 * @param box {Box}
 */
BoxComponent.invoke = function(methodName, box) {
    var component = box.getComponent();

    if (component && component[methodName]) {
        component[methodName].apply(component, [box]);
    }

    return box;
};

/**
 * invokes onClose for the Component inside the Box instance
 * @param box {Box}
 * @returns {Box}
 */
BoxComponent.destroy = function (box) {
    return BoxComponent.invoke("onClose", box);
};

/**
 * invokes onFlowChange for the Component inside the Box instance
 * @param box
 * @returns {*}
 */
BoxComponent.reflow = function(box) {
    return BoxComponent.invoke("onReflow", box);
};

/**
 * invokes onMaximize for the Component inside the Box instance
 * @param box
 * @returns {*}
 */
BoxComponent.maximize = function(box) {
    return BoxComponent.invoke("onMaximize", box);
};

/**
 * invokes onMinimize for the Component inside the Box instance
 * @param box
 * @returns {*}
 */
BoxComponent.minimize = function(box) {
    return BoxComponent.invoke("onMinimize", box);
};

/**
 * invokes onRestore for the Component inside the Box instance
 * @param box
 * @returns {*}
 */
BoxComponent.restore = function(box) {
    return BoxComponent.invoke("onRestore", box);
};

/**
 * invokes onRestore for the Component inside the Box instance
 * @param box
 * @returns {*}
 */
BoxComponent.show = function(box) {
    return BoxComponent.invoke("onShow", box);
};

/**
 * invokes onRestore for the Component inside the Box instance
 * @param box
 * @returns {*}
 */
BoxComponent.hide = function(box) {
    return BoxComponent.invoke("onHide", box);
};

exports.ElementWrapper = ElementWrapper;

/**
 * @name ElementWrapper
 * @constructor
 * @param [element] {HTMLElement} Optional so that the class can be used by others
 */
function ElementWrapper(element) {
    /**
     * the HTMLElement of the Box instance - DOM
     * @private
     * @type {HTMLDivElement}
     */
    this._element = element || document.createElement("div");
}

/**
 * @param width {Number}
 * @private
 */
ElementWrapper.prototype._setElementWidth = function (width) {
    this.getElement().style.width = (typeof width === 'string' ? width : width + "px");
    return this;
};

/**
 * Returns the height of the element
 * @returns {String}
 */
ElementWrapper.prototype.getElementHeight = function() {
    return this.getElement().style.height;
};

/**
 * Returns the width of the element
 * @returns {String}
 */
ElementWrapper.prototype.getElementWidth = function() {
    return this.getElement().style.width;
};

/**
 * @param height {Number}
 * @private
 */
ElementWrapper.prototype._setElementHeight = function (height) {
    this.getElement().style.height = (typeof height === 'string' ? height : height + "px");
    return this;
};

/**
 * Set new dimension for the elements
 * @param width {Number}
 * @param height {Number}
 * @private
 */
ElementWrapper.prototype.setElementDimension = function (width, height) {
    return this._setElementWidth(width)._setElementHeight(height);
};

/**
 * returns the DOM Element of the Box
 * @return {HTMLElement}
 */
ElementWrapper.prototype.getElement = function () {
    return this._element;
};

/**
 * adds a class to the HTMLElementWrapper if it isn't
 * @param className {String} class name to add
 */
ElementWrapper.prototype.addClass = function (className) {
    var attribute = this.getElement().getAttribute("class"),
        classes = (attribute ? attribute.split(" ") : []);

    if (classes.indexOf(className) < 0) {
        classes.push(className);
        this.getElement()
            .setAttribute("class", classes.join(" "));
    }

    return this;
};
/**
 * remove a class to the HTMLElementWrapper
 * @param className {String} class name to remove
 */
ElementWrapper.prototype.removeClass = function (className) {

    var attribute = this.getElement().getAttribute("class"),
        keep = [];

    (attribute ? attribute.split(" ") : []).forEach(function(currentClassName) {
        if (currentClassName !== className) {
            keep.push(currentClassName);
        }
    });

    this.getElement().setAttribute("class", keep.join(" "));
    return this;
};

/**
 * determines whether the Box DOM Element's class attribute contains the specified string
 * @param className {String} class name to add
 */
ElementWrapper.prototype.hasClass = function (className) {
    return this.getElement().getAttribute("class").indexOf(className) > -1;
};

/**
 * returns an attribute of the DOM Element of the Box
 * @param attribute {String} name of the attribute
 * @return {String}
 */
ElementWrapper.prototype.getAttribute = function (attribute) {
    return (this.getElement().getAttribute(attribute) || "");
};

/**
 * sets an attribute of the DOM Element of the Box
 */
ElementWrapper.prototype.setAttribute = function (attribute, value) {
    if (value) {
        this.getElement()
            .setAttribute(attribute, value.toString());
    }

    return this;
};

/**
 * Append a node to the box element
 * @param node {HTMLElement}
 */
// TODO support nodeList
ElementWrapper.prototype.append = function (node) {
    this.getElement().appendChild(node);
    return this;
};

/**
 * returns a data attribute of the DOM Element of the Box
 * @param attribute {String} name of the attribute
 * @return {String}
 */
ElementWrapper.prototype.getDataAttribute = function (attribute) {
    return this.getElement().getAttribute("data-" + attribute);
};

/**
 * sets a data attribute on the DOM Element of the Box
 * @param attribute {String} name of the attribute
 * @param value {*} any serializable Object (implements or overrides toString() )
 */
ElementWrapper.prototype.setDataAttribute = function (attribute, value) {
    if (value) {
        this.getElement()
            .setAttribute("data-" + attribute, value);
    }

    return this;
};

/**
 * Set multiple properties on an element
 * @param properties
 */
ElementWrapper.prototype.css = function(properties) {

    var element = this.getElement();
    var prop;

    for (prop in properties) {
        element.style[prop] = properties[prop];
    }

    return this;
};

/**
 * sets or returns the text content of the Box instance
 * @param text {String} name of the attribute
 * @return {String|undefined}
 */
ElementWrapper.prototype.text = function (text) {
    var element = this.getElement();

    if (typeof text !== "string") {
        return element.innerText;
    } else {
        element.innerText = text;
    }

    return this;
};

/**
 * sets or returns the html content of the Box instance
 * @param html {String} name of the attribute
 * @return {String|undefined}
 */
ElementWrapper.prototype.html = function (html) {
    var element = this.getElement();

    if (typeof html !== "string") {
        return element.innerHTML;
    } else {
        element.innerHTML = html;
    }

    return this;
};

/**
 * Hide the HTML representation of the Box instance
 */
ElementWrapper.prototype.hide = function () {
    this.getElement().style.display = 'none';
    BoxComponent.hide(this);
    this.emit(EventEmitter.ON_HIDE);
    return this;
};

/**
 * Show the HTML representation of the Box instance
 */
ElementWrapper.prototype.show = function () {
    this.getElement().style.display = '';
    BoxComponent.show(this);
    this.emit(EventEmitter.ON_SHOW);
    return this;
};

/**
 * Toggle the visibility of the Box instance
 */
ElementWrapper.prototype.toggle = function () {
    return (this.getElement().style.display === 'none') ? this.show() : this.hide();
};

/**
 * Maximize the visual representation of the Box instance
 */
ElementWrapper.prototype.maximize = function () {
    this.css({
            position: "absolute",
            left: "0",
            top: "0",
            right: "0",
            bottom: "0",
            zIndex: Box.getZIndex()
        })
        .addClass("maximized")
        .setElementDimension(document.body.clientWidth, document.body.clientWidth)
        .emit(EventEmitter.ON_MAXIMIZE);

    BoxComponent.maximize(this);
    return this;
};

/**
 * Minimize the visual representation of the Box instance
 */
ElementWrapper.prototype.minimize = function () {
    this.setElementDimension(this.width.getMinimumValue(), this.height.getMinimumValue())
        .addClass("minimized")
        .emit(EventEmitter.ON_MINIMIZE);

    BoxComponent.minimize(this);
    return this;
};

/**
 * Restore the visual representation of the Box instance to its original configuration
 */
ElementWrapper.prototype.restore = function () {
    this.css({
            position: "relative",
            left: "auto",
            top: "auto",
            bottom: "auto",
            right: "auto",
            zIndex: "auto"
        })
        .removeClass("maximized")
        .removeClass("minimized")
        .setElementDimension(this.width.getValue(), this.height.getValue())
        .emit(EventEmitter.ON_RESTORE);

    BoxComponent.restore(this);

    return this;
};

exports.ParentElementWrapper = ParentElementWrapper;

/**
 * @name ParentElementWrapper
 * @constructor
 * @param parent {HTMLElement}
 */
function ParentElementWrapper(parent) {
    /**
     * the HTMLElement - DOM
     * @private
     * @type {Object}
     */
    this._parentElement = parent;
}

/**
 * returns the parent DOM Element of the Box
 * @return {HTMLElement}
 */
ParentElementWrapper.prototype.getParentElement = function () {
    return (this._parentElement || getBody());
};

/**
 * sets the parent DOM Element of the Box
 * @param parent {HTMLElement} the parent DOM HTMLElementWrapper
 */
ParentElementWrapper.prototype.setParentElement = function (parent) {
    this._parentElement = parent;
//    var element = this.getElement();
//
//    if (element.parentElement !== parent && this._parentElement !== parent) {
//        this._parentElement = parent;
//        this._parentElement.appendChild(element);
//    }

    return this;
};

exports.Serializer = Serializer;

/**
 * Provides serializer method for each Box instance to serialize their state
 * @constructor Serializer
 * @mixin
 * @static
 */
function Serializer() {}

/**
 * serializes a hierarchy of Box instances
 * @param format {String} either "xml" or "json"
 * @param name {String} the name of the Box instance in the collection
 * @returns {String}
 */
Serializer.prototype.serialize = function (format, name) {
    var serializedBox;

    if (format === Serializer.JSON) {
        serializedBox = Serializer.toJSON(this, name);
    } else {
        serializedBox = Serializer.toXML(this, name);
    }

    return serializedBox;
};

/**
 * serializes the given Box instance to JSON format
 * @param box {boxxer.Box} the Box to serialize
 * @param name {String} the name of the Box instance in the collection
 * @returns {string}
 */
Serializer.toJSON = function (box, name) {
    var child;
    var children;
    var view = box.view;
    var childCount = box.getChildCount();
    var decorators = box.getDecorators();
    var json = "{" +
        "\"id\":" + Number(box.getId().replace("bbox_", "")) + "," +
        "\"flow\":\"" + box.getFlowDirection() + "\"," +
        Serializer.getJSONAttributes(box);

    name = name || box.getName() || null;

    if (typeof name === "string" && name !== "") {
        json += ",\"name\":\"" + name + "\"";
    }

    if (decorators.length > 0) {
        json += ",\"decorators\":[";
        json += decorators.join(",");
        json +="]";
    }

    if (childCount > 0) {
        json += ",\"children\":[";
        children = box.getChildren();

        for (child in children) {
            if (children.hasOwnProperty(child)) {
                json += children[child].serialize(Serializer.JSON, child);
                childCount--;

                if (childCount > 0) {
                    json += ",";
                }
            }
        }

        json += "]";
    }

    if (view instanceof ViewContainer) {
        json += ", view:" + view.serialize();
    }

    json += "}";

    return json;
};

/**
 * serializes the given Box instance to XML format
 * @param box {boxxer.Box} the Box to serialize
 * @param name {String} the name of the Box instance in the collection
 * @returns {string}
 */
Serializer.toXML = function (box, name) {
    var child;
    var children;
    var decorators = box.getDecorators();
    var xml = "<bbox" +
        " id='" + Number(box.getId().replace("bbox_", "")) + "'" +
        " flow='" + box.getFlowDirection() + "'";

    if (typeof name === "string" && name !== "") {
        xml += " name='" + name + "'";
    }

    xml += Serializer.getXMLAttributes(box) + ">";

    if (decorators.length > 0) {
        xml += " decorators='";
        xml += decorators.join(",");
        xml +="'";
    }

    if (box.getChildCount()) {
        children = box.getChildren();

        for (child in children) {
            if (children.hasOwnProperty(child)) {
                xml += children[child].serialize(Serializer.XML, child);
            }
        }
    }

    xml += "</bbox>";

    return xml;
};

/**
 * returns the dimension attributes for the given Box instance for JSON format
 * @param box {boxxer.Box}
 * @returns {string}
 */
Serializer.getJSONAttributes = function (box) {
    return "\"width\":" + box.getWidth().getSerializedValue() + "," +
        "\"height\":" + box.getHeight().getSerializedValue() + "";
};

/**
 * returns the dimension attributes for the given Box instance for XML format
 * @param box {boxxer.Box}
 * @returns {string}
 */
Serializer.getXMLAttributes = function (box) {
    return " width='" + box.getWidth().getSerializedValue() + "' " +
        "height='" + box.getHeight().getSerializedValue() + "'";
};

/**
 * deserializes the serialized Box hierarchy
 * @param serialized {String} hierarchy of Boxes
 * @returns {Object|Element}
 */
Serializer.deserialize = function (serialized) {
    var div;
    var box;
    var test;
    var result;
    var format;

    try {
        test = JSON.parse(serialized);

        if (test instanceof Object) {
            format = Serializer.JSON;
            result = test;
        }
    } catch (e) {
        div = document.createElement("div");
        div.innerHTML = serialized;
        box = (div.firstElementChild || div.children[0]);

        if (box && box.tagName.toLowerCase() === "bbox") {
            format = Serializer.XML;
            result = box;
        }
    }

    if (result !== undefined) {
        result = Serializer.buildHierarchy(result, format);
    }

    return result;
};

/**
 * constructs and returns a hierarchy of box instances based on the arguments
 * @param hierarchy {Object|Element}
 * @param format {String}
 * @returns {boxxer.Box|undefined}
 */
Serializer.buildHierarchy = function (hierarchy, format) {
    var box = new Box();
    var childBox;
    var decorators;
    var child;
    var i;

    if (format === Serializer.JSON) {
        box = new Box();
        box.setFlowDirection(hierarchy.flow);
        box.setWidth(hierarchy.width);
        box.setHeight(hierarchy.height);
        box.addClass(hierarchy.class);

        if (hierarchy.decorators) {
            decorators = hierarchy.decorator.replace(" ", "").split(",");

            while (decorators.length > 0) {
                box.addDecorator(decorators.shift());
            }
        }

        if (hierarchy.children && hierarchy.children.length > 0) {
            for (i = 0; i < hierarchy.children.length; i++) {
                child = hierarchy.children[i];
                childBox = box.addBox(Serializer.buildHierarchy(child, format), child.name);
            }
        }
    } else if (format === Serializer.XML) {
        box.setFlowDirection(hierarchy.getAttribute("flow"));
        box.setWidthDimension(hierarchy.getAttribute("width"));
        box.setHeightDimension(hierarchy.getAttribute("height"));
        box.addClass(hierarchy.getAttribute("class"));

        if (hierarchy.getAttribute("decorators")) {
            decorators = hierarchy.getAttribute("decorators").replace(" ", "").split(",");

            while (decorators.length > 0) {
                box.addDecorator(decorators.shift());
            }
        }

        if (hierarchy.children && hierarchy.children.length) {
            for (i = 0; i < hierarchy.children.length; i++) {
                child = hierarchy.children[i];
                childBox = box.addBox(Serializer.buildHierarchy(child, format), child.getAttribute("name"));
            }
        }
    }

    return box;
};

/**
 * @static
 * @type {string}
 */
Serializer.XML = "xml";

/**
 * @static
 * @type {string}
 */
Serializer.JSON = "json";

exports.Data = Data;

function Data() {
    this.url = "/persist";
}

exports.BoxRenderer = BoxRenderer;

/**
 * This class is responsible for rendering a Box instance and its child Box instances recursively
 * @static
 * @constructor BoxRenderer
 */
function BoxRenderer() {}

/**
 * set the given element as an inline-block element
 * @param element {HTMLElement}
 */
BoxRenderer.setElementInline = function (element) {
    element.style.display = "inline-block";
    element.style.verticalAlign = "top";
};

/**
 * renders a given Box instance to the DOM
 * @param box {Box} Box to render
 * @param parent {HTMLElement} the parent HTMLElement to render in
 * @param flowDirection {String} the direction of the flow inside the parent
 */
BoxRenderer.render = function (box, parent, flowDirection) {
    if (!(box instanceof Box)) {
        throw new TypeError("Invalid argument - not a box!");
    }

    var element = box.getElement();
    var view = box.view;

    // TODO: apply overflow: auto when the Box instance current size
    // is smaller then the total width of the child FixBox instances
    // otherwise the layout collapses
    // eElement.style.overflow = "auto";

    if (typeof flowDirection === "undefined" ||
        typeof parent === "undefined")
    {
        parent = box.getParentElement();
        flowDirection = box.getFlowDirection();

        if (flowDirection === Box.FLOW_HORIZONTAL) {
            BoxRenderer.setElementInline(element);
        }

        box.setDimensions(parent.offsetWidth, parent.offsetHeight);
    } else {
        if (flowDirection === Box.FLOW_HORIZONTAL) {
            BoxRenderer.setElementInline(element);
        }
    }

    /* TODO:
     *    We might want to separate the update and the render methods.
     *
     *    Reason:
     *        Event subscriptions. We would be able to separate event subscriptions
     *        for both the render and the update events
     *
     * do not append if already appended - makes perfect sense...
     */
    if (element.parentNode !== parent) {
        if (element.parentNode) {
            element.parentNode.removeChild(element);
        }

        parent.appendChild(element);
    }

    if (!box.isRendered) {
        BoxRenderer._applyDecorators(box);
    }

    BoxRenderer._postRender(box, view, element);
};

/**
 * applies (engages) the added decorators for a Box
 * @private
 * @param box {Box}
 */
BoxRenderer._applyDecorators = function (box) {
    box.getDecoratorNames().forEach(function(decoratorName) {
        box._decorators.push(Decorator.get(decoratorName, box));
    });
};

/**
 * render after the Box instance itself has been rendered
 * @private
 * @param box {Box}
 * @param view {ViewContainer}
 * @param element {HTMLElement}
 */
BoxRenderer._postRender = function (box, view, element) {
    var viewContent;
    var tempElement;

    if (box.getChildCount()) {
        this._renderChildren(box, element, box.getFlowDirection());
    }

    //TODO: test this part because this has been implemented quickly!
    if (view instanceof ViewContainer) {
        viewContent = view.render(element);

        if (viewContent) {
            if (viewContent instanceof Node) {
                element.appendChild(viewContent);
            } else if (typeof viewContent === "string") {
                tempElement = document.createElement("div");
                tempElement.innerHTML = viewContent;
                //append content wrapper firstChildElement
                element.appendChild(tempElement.firstElementChild);
            }
        }
    }
};

/**
 * prepares the child Box instances and all the required properties  for rendering
 * @private
 * @param box {Box}
 * @param element {HTMLElement}
 * @param flowDirection {String}
 */
// the real percentage values based on the element size, therefore weight
// dimensions cannot work properly with percentage dimensions
BoxRenderer.resolveAndSortChildren = function (box, element, flowDirection) {
    var order = [];
    var isHorizontal = flowDirection === Box.FLOW_HORIZONTAL;
    var property = (isHorizontal ? "width" : "height");
    var elementDimension = element["offset" + (isHorizontal ? "Width" : "Height")];
    var children = box.getChildren();
    var pxBoxes = {}, pcBoxes = {}, wBoxes = {};
    var percents = 0, pixels = 0, weights = 0;
    var dimension, child, c;

    for (c in children) {
        if (children.hasOwnProperty(c)) {
            child = children[c];
            dimension = child[property];

            switch (dimension.getType()) {
                case Dimension.PERCENT:
                    pcBoxes[c] = child;
                    percents += Math.floor(elementDimension * (dimension.getValue() / 100));
                    break;
                case Dimension.PIXEL:
                    pxBoxes[c] = child;
                    pixels += dimension.getValue();
                    break;
                default:
                    wBoxes[c] = child;
                    weights += dimension.getValue();
            }

            order.push(c);
        }
    }

    return {
        order: order,
        method: (flowDirection === Box.FLOW_VERTICAL ? "Width" : "Height"),
        dimension: (flowDirection === Box.FLOW_HORIZONTAL ? "Width" : "Height"),
        pixelBoxes: pxBoxes,
        percentBoxes: pcBoxes,
        weightBoxes: wBoxes,
        percents: percents,
        weights: weights,
        pixels: pixels
    }
};

/**
 * renders the children of the Box
 * @private
 * @param box {Box}
 * @param element {HTMLElement}
 * @param flowDirection {String}
 */
BoxRenderer._renderChildren = function (box, element, flowDirection) {
    var sorted = this.resolveAndSortChildren(box, element, flowDirection);
    var children = box.getChildren();
    var order = sorted.order;
    var WEIGHT = Dimension.WEIGHT;
    var stretch,
        total,
        dimensionType,
        available,
        width,
        height,
        calculatedWidth,
        calculatedHeight,
        child;

    //taking the proper dimension from the parent to stretch to and count with
    if (flowDirection === Box.FLOW_HORIZONTAL) {
        stretch = element.offsetHeight;
        total = element.offsetWidth;
    } else {
        stretch = element.offsetWidth;
        total = element.offsetHeight;
    }

    //available space for weighted flexible dimensions
    available = total - sorted.percents - sorted.pixels;

    while (order.length > 0) {
        child = children[order.shift()];
        width = child.width;
        height = child.height;

        //calculating dimensions based on the dimension type
        if (flowDirection === Box.FLOW_HORIZONTAL) {
            dimensionType = width.getType();
            //if the dimension is weighted, use the available space, otherwise use the total
            calculatedWidth = width.calculate(
                dimensionType === WEIGHT ? available : total, sorted.weights);
            calculatedHeight = height.calculate(stretch, 1);
        } else {
            dimensionType = height.getType();
            calculatedWidth = width.calculate(stretch, 1);
            //if the dimension is weighted, use the available space, otherwise use the total
            calculatedHeight = height.calculate(
                dimensionType === WEIGHT ? available : total, sorted.weights);
        }

        //setting the dimensions
        child.setDimensions(calculatedWidth, calculatedHeight);
        child.render();
    }
};

exports.Dimension = Dimension;

/**
 * @param arg
 * class is used and responsible for managing the rendered width or height of a Box instance.
 *
 * Each Box instance should have a width and a height
 * Dimension instance which will calculate its own pixel/percent/weight
 * values during the rendering process
 *
 * Every sizing calculation and info should be stored here instead of the Box class!
 * @constructor Dimension
 */
function Dimension(arg) {
    var parsed = this._parse(arg);
    var value = parseInt(parsed.value);

    /**
     * @private
     * @type {Number}
     */
    this._minValue = Box.MIN_DIMENSION;

    /**
     * @private
     * @type {Number}
     */
    this._value = (!!value ? value : 1);

    /**
     * @private
     * @type {String}
     */
    this._type = undefined;

    switch (parsed.type) {
        case "%":
            this._type = Dimension.PERCENT;
            break;
        case "px":
            this._type = Dimension.PIXEL;
            break;
        default:
            this._type = Dimension.WEIGHT;
    }
}

/**
 * parses the given argument
 * @private
 * @param value {String}
 * @returns {{value: {Number}, type: {String}}
 */
Dimension.prototype._parse = function (value) {
    var result = (value || "").toString().split(/(\%|px)/);
    return {
        value: result[0],
        type: result[1]
    }
};

/**
 * returns the type of the Dimension instance
 * @public
 * @returns {string}
 */
Dimension.prototype.getType = function () {
    return (this._type || "");
};

/**
 * returns the minimum value of the Dimension instance
 * @public
 * @returns {Number}
 */
Dimension.prototype.getMinimumValue = function () {
    return this._minValue;
};

/**
 * set the minimum value of the Dimension instance (useful to set custom minimized value)
 * @public
 * @returns {Number}
 */
Dimension.prototype.setMinimumValue = function (minValue) {
    this._minValue = minValue;
};

/**
 * returns the value of the Dimension instance
 * @public
 * @returns {Number}
 */
Dimension.prototype.getValue = function () {
    return this._value;
};

/**
 * calculates the proper value for an specified dimension and/or for a maximum weight
 * @public
 * @param availableSize {Number} total dimension to compare the Dimension values to
 * @param [totalWeight] {Number} * optional - maximum weight
 * @returns {Number}
 */
Dimension.prototype.calculate = function (availableSize, totalWeight) {
    var type = this.getType();
    var value = this.getValue();
    var hideSnapDimension = 5;
    var minValue = parseInt(this._parse(this.getMinimumValue()).value);
    var result = value;

    if (availableSize <= hideSnapDimension && type === Dimension.WEIGHT) {
        result = 0;
    } else {
        switch (type) {
            case Dimension.PERCENT:
                result = availableSize * (value / 100);
                break;
            case Dimension.WEIGHT:
                if (value > totalWeight) {
                    value = totalWeight;
                }

                result = (availableSize / totalWeight) * value;
                break;
        }

        if (result < minValue) {
            result = minValue;
        }
    }

    return Math.floor(result);
};

/**
 * Returns the serialized value of the Dimension
 * @returns {String}
 */
Dimension.prototype.getSerializedValue = function () {
    var type = this.getType();
    var serialized = this.getValue();

    if (type !== Dimension.WEIGHT) {
        serialized += this.getType();
    }

    return serialized;
};

/**
 * @static
 * @type {string}
 */
Dimension.PERCENT = "%";

/**
 * @static
 * @type {string}
 */
Dimension.WEIGHT = "weight";

/**
 * @static
 * @type {Number}
 */
Dimension.DEFAULT_WEIGHT = 1;

/**
 * @static
 * @type {string}
 */
Dimension.PIXEL = "px";

exports.ViewContainer = ViewContainer;

/**
 * class to maintain custom user views inside Box and Panel instances
 * @constructor ViewContainer
 */
function ViewContainer(parent) {
    this.box = new Box(1, 1, parent);
}

/**
 * returns the Box in the ViewContainer
 * @returns {Box}
 */
ViewContainer.prototype.getBox = function () {
    return this.box;
};

/**
 * renders the ViewContainer, invoked when the Panel or Box finished rendering
 */
ViewContainer.prototype.render = function () {
    return this.box.render().getElement();
};

/**
 * destroys the ViewContainer and the contained Box
 */
ViewContainer.prototype.destroy = function () {
    return this.box.destroy();
};

/**
 * serializes the ViewContainer
 * @returns {string}
 */
ViewContainer.prototype.serialize = function () {
    return '\"\"';
};
boxxer.createDecorator("Drag", {

    initialize: function () {

        var element = this.box.getElement();

        element.setAttribute("draggable", "true");

        new DOMEvent(element)
            .on("dragstart", this.onDragStart.bind(this))
            .on("dragend", this.onDragEnd.bind(this));
    },

    onDragStart: function() {
        Box.dragTarget = this.box;
    },

    onDragEnd: function(event) {

        event.preventDefault();

        if (Box.dropTarget && Box.dragTarget) {

            Box.dropTarget.append(Box.dragTarget.getElement());

            Box.moveBox(Box.dragTarget, Box.getById(Box.dragTarget.getParentElement().getAttribute("data-box-id")), Box.dropTarget);

            Box.dropTarget = undefined;
            Box.dragTarget = undefined;
        }
    }
});
boxxer.createDecorator("Drop", {

    initialize: function () {

        new DOMEvent(this.box.getElement())
            .on("dragenter", this.onDragEnter.bind(this));
    },

    onDragEnter : function() {
        Box.dropTarget = this.box;
    }
});
boxxer.createDecorator("PanelControls", {

    events: {
        click: {
            ".panel-minimize": "onMinimize",
            ".panel-maximize": "onMaximize",
            ".panel-close": "onClose"
        }
    },

    initialize: function () {
        this.box.css({position:"relative"});
        this.box.append(this.template.getElement());

        this.box.width.setMinimumValue(this.box.width.getValue());
        this.box.height.setMinimumValue(this.template.getElementHeight());

        this.minimized = false;
        this.maximized = false;
    },

    reset: function(property) {
        this[property] = false;
        this.box.restore();
    },

    onMinimize: function() {
        this.minimized = !this.minimized;
        if (this.minimized) {
            this.reset("maximized");
            this.box.minimize();
        } else {
            this.box.restore();
        }
    },

    onMaximize: function() {
        this.maximized = !this.maximized;
        if (this.maximized) {
            this.reset("minimized");
            this.box.maximize();
        } else {
            this.box.restore();
        }
    },

    onClose: function() {
        this.box.destroy();
    },

    getTemplate: function () {
        return new ElementWrapper(document.createElement("div"))
            .addClass("panel-controls")
            .html(
                '
' + (this.box.getName() || this.box.getId()) + '
' +
                '
' +
                    '<button class="panel-minimize">-</button>' +
                    '<button class="panel-maximize">+</button>' +
                    '<button class="panel-close">x</button>' +
                '
'
            );
    }
});
exports.Dialog = Dialog;

/**
 * @param [width] {Number|String}
 * @param [height] {Number|String}
 * @param [left] {Number|String}
 * @param [right] {Number|String}
 * @constructor Dialog
 */
function Dialog(width, height, left, right) {
    ElementWrapper.call(this);
    Adjustable.call(this);

    var element = this.getElement();
    element.setAttribute("class", "boxxer-Dialog");
    element.style.position = "absolute";
    element.style.zIndex = Box.getZIndex();

    renderer.appendChild(element);
    renderer.removeChild(element);

    this.container = undefined;
    this.width = new Dimension(width);
    this.height = new Dimension(height);
    this.left = left || Dialog.CENTER;
    this.right = right || Dialog.CENTER;
    this.viewContainer = new ViewContainer(element);
}

mix(Dialog, ElementWrapper);
mix(Dialog, Adjustable);

/**
 * opens the Dialog
 * @return {Dialog}
 */
Dialog.prototype.open = function () {
    var element = this.getElement();
    var container = this.container || getBody();
    var availableWidth = container.offsetWidth;
    var availableHeight = container.offsetHeight;
    var width = this.width.calculate(availableWidth, 1);
    var height = this.height.calculate(availableHeight, 1);

    this.setWidth(width);
    this.setHeight(height);

    element.style.left = ((availableWidth / 2) - (width / 2)) + "px";
    element.style.top = ((availableHeight / 2) - (height / 2)) + "px";

    this.renderViewContent(element);

    container.appendChild(element);

    return this;
};

/**
 * sets the container of the Dialog instance
 * @param container {Box|HTMLElement}
 * @returns {Dialog}
 */
Dialog.prototype.setContainer = function (container) {
    if (!(container instanceof Box || container instanceof HTMLElement)) {
        throw new TypeError("Container must be a Box or a HTMLElement instance!");
    }

    this.container = container;

    return this;
};

/**
 * renders the ViewContent into the Dialog
 * @param element {HTMLElement}
 */
Dialog.prototype.renderViewContent = function (element) {
    var viewContent = this.viewContainer.render();
    var tempElement;

    if (viewContent) {
        if (viewContent instanceof Node) {
            element.appendChild(viewContent);
        } else if (typeof viewContent === "string") {
            tempElement = document.createElement("div");
            tempElement.innerHTML = viewContent;

            element.appendChild(tempElement.firstElementChild);
        }
    }
};

/**
 * closes the dialog and destroys the Box
 */
Dialog.prototype.close = function () {
    this.viewContainer.destroy();
    removeElement(this.getElement());
};

/**
 * @static
 * @type {String}
 */
Dialog.CENTER = "center";

exports.Box = Box;

/**
 * Abstract class that provides the basic attributes for each Box instance
 * @constructor Box
 * @param width {String|Number}
 * @param height {String|Number}
 * @param parent {HTMLElement|undefined}
 */
function Box(width, height, parent) {
    //mixin constructors
    ElementWrapper.call(this);
    ParentElementWrapper.call(this, parent);
    EventEmitter.call(this);
    BoxComponent.call(this);

    /**
     * id of the Box
     * @private
     * @type {Object}
     */
    this._id = Box.generateUniqueBoxId();

    /**
     * Optional custom name  for the box. Use the setter if you wish to use one.
     * @type {null}
     * @private
     */
    this._name = null;

    /**
     * @private
     * @type {Object}
     */
    this._children = {};

    /**
     * property for boxxer.view.View instance to serialize
     * @type {boxxer.view.ViewContainer|undefined}
     */
    this.view = undefined;

    /**
     * width of the Box
     * @type {b.render.Dimension}
     */
    this.width = new Dimension(width);

    /**
     * height of the Box
     * @type {b.render.Dimension}
     */
    this.height = new Dimension(height);

    /**
     * array of decorator names to apply after rendering
     * @private
     * @type {Array}
     */
    this._decoratorNames = [];

    /**
     * array of initialized decorators
     * @type {String}
     * @private
     */
    this._decorators = [];

    /**
     * the direction inside the Box
     * @private
     * @type {Object}
     */
    this._flowDirection = Box.FLOW_VERTICAL;

    /**
     * @private
     * @type {Boolean}
     */
    this.isRendered = false;

    //initialize Box
    this.addClass("boxxer-Box");
    this.setDataAttribute("box-id", this.getId());

    //registering Box
    Box._registry[this.getId()] = this;

    return this;
}

mix(Box, Adjustable);
mix(Box, ElementWrapper);
mix(Box, ParentElementWrapper);

mix(Box, Layout);
mix(Box, Serializer);
mix(Box, EventEmitter);
mix(Box, BoxComponent);

/**
 * adds the decorator specified to the Box instance
 * @param decoratorName {String}
 * @returns {Box}
 */
Box.prototype.addDecorator = function (decoratorName) {
    this._decoratorNames.push(decoratorName);
    return this;
};

/**
 * returns an array of decorator names registered for the Box instance
 * @returns {Array}
 */
Box.prototype.getDecoratorNames = function () {
    return this._decoratorNames;
};

/**
 * returns an array of decorators instances applied on the Box instance
 * @returns {Array}
 */
Box.prototype.getDecorators = function () {
    return this._decorators || [];
};

/**
 * return the flow direction of the box
 * @returns {Object}
 */
Box.prototype.getFlowDirection = function () {
    return this._flowDirection;
};

/**
 * Set the flow direction for the box
 * @param flowDirection {String}
 */
Box.prototype.setFlowDirection = function (flowDirection) {
    this._flowDirection = (flowDirection || Box.FLOW_VERTICAL);
    BoxComponent.reflow(this);
    return this;
};

/**
 * creates a new Dimension for width property
 * @param value {string|Number}
 */
Box.prototype.setWidthDimension = function (value) {
    this.width = new Dimension(value);
    return this;
};

/**
 * creates a new Dimension for width property
 * @param value {string|Number}
 */
Box.prototype.setHeightDimension = function (value) {
    this.height = new Dimension(value);
    return this;
};

/**
 * adds a new child to the current box instance
 * @param width {Number|String} width argument
 * @param height {Number|String} width argument
 * @param name {String} name of the new instance in the collection
 * @returns {Box}
 */
Box.prototype.addChild = function (width, height, name) {
    var box = new Box(width, height, this.getElement());
    this.addBox(box, name);
    return this;
};

/**
 * adds the given Box to the children
 * @param name {String} the child's name
 * @param box {Box} the child Box
 * @return {Box}
 */
Box.prototype.addBox = function (box, name) {
    if (!(box instanceof Box)) {
        throw new TypeError("Argument is not a Box!");
    }

    box.setParentElement(this.getElement());

    if (name) {
        this.setName(name);
    }

    this.getChildren()[box.getName() || box.getId()] = box;

    return this;
};

/**
 * Get the box custom name. Returns null if name was set.
 * @returns {null|String}
 */
Box.prototype.getName = function() {
    return this._name;
};

/**
 * Set a custom name for the Box and register it.
 * @param name {String}
 */
Box.prototype.setName = function(name) {
    if (Box._nameRegistry[name]) {
        throw "Box name already exists: " + name;
    }

    this._name = name;

    Box._nameRegistry[name] = this.getId();

    return this;
};

/**
 * returns the Box name
 * @return {String}
 */
Box.prototype.getId = function () {
    return this._id;
};

/**
 * returns a child from the BoxSet
 * @param name {String} the name of the child
 * @return {Box}
 */
Box.prototype.getChild = function (name) {
    return this.getChildren()[name];
};

/**
 * returns the children
 * @return {Object}
 */
Box.prototype.getChildren = function () {
    return this._children;
};

/**
 * returns the number of children the Box has
 * @return {Number}
 */
Box.prototype.getChildCount = function () {
    return Object.keys(this.getChildren()).length;
};

/**
 * removes a child Box
 * @param name {String} the name of the child
 */
Box.prototype.removeChild = function (name) {
    var children = this.getChildren();
    children[name].close();
    delete children[name];
    return this;
};

/**
 * Render the box and its children to the document
 */
Box.prototype.render = function (autoResize) {
    var parent = this.getParentElement();
    var boxId = parent.getAttribute("data-box-id");
    var parentBox = Box.getById(boxId);
    var eventType = EventEmitter.ON_RENDER;
    var flowDirection;

    if (parentBox instanceof Box) {
        flowDirection = parentBox.getFlowDirection();
    }

    BoxRenderer.render(this, parent, flowDirection);
    BoxComponent.render(this);

    if (this.isRendered) {
        eventType = EventEmitter.ON_UPDATE;
    } else {
        this.isRendered = true;
    }

    if (autoResize) {
        new DOMEvent(window).on("resize", function() {
            this.render();
        }.bind(this));
    }

    this.emit(eventType);

    return this;
};

/**
 * destroys and removes the Box
 */
Box.prototype.destroy = function () {
    delete Box._nameRegistry[this.getName()];
    delete Box._registry[this.getId()];
    BoxComponent.destroy(this);
    removeElement(this.getElement());
};

/**
 * @static
 * @type {Number}
 */
Box.MIN_DIMENSION = "10px";

/**
 * @static
 * @type {String}
 */
Box.FLOW_VERTICAL = "vertical";

/**
 * @static
 * @type {String}
 */
Box.FLOW_HORIZONTAL = "horizontal";

/**
 * @static
 * @type {Object}
 */
Box._registry = {};

/**
 * @static
 * @type {Object}
 */
Box._nameRegistry = {};

/**
 * static counter for Box ids
 * @static
 * @private
 * @type {Number}
 */
Box.REG_PREFIX = "bbox_";

/**
 * static counter for Box ids
 * @static
 * @private
 * @type {Number}
 */
Box._id = 0;

/**
 * static counter for zIndex
 * @static
 * @private
 * @returns {number}
 */
Box._zIndex = 666;

/**
 * @beta
 * Used by decorator to track which box is the current dropTarget
 * @type {null}
 * @private
 */
// TODO better solution?
Box.dropTarget = null;

/**
 * @beta
 * Used by decorator to track which box is the current dragTarget
 * @type {null}
 * @private
 */
// TODO better solution?
Box.dragTarget = null;

/**
 * Return the current zIndex and increase it
 * @returns {number}
 */
Box.getZIndex = function() {
    var zIndex = Box._zIndex;
    Box._zIndex++;
    return zIndex;
};

/**
 * generates a unique "box_[...]"id
 * @static
 * @return {String}
 */
Box.generateUniqueBoxId = function () {
    return Box.REG_PREFIX + Box._id++;
};

/**
 * removes a Box from the registry
 * @param id {String} id of the Box to remove
 */
Box.removeBox = function (id) {
    delete Box._registry[id];
};

/**
 * Move a box from one parent box to another
 * @param box
 * @param origin
 * @param destination
 */
Box.moveBox = function(box, origin, destination) {
    box.setParentElement(destination.getElement());
    destination.addBox(box);
    delete origin.getChildren()[box.getId()];
};

/**
 * returns a registered Box from the registry by id
 * @param id {String} the Box id
 * @return {Box}
 */
Box.getById = function (id) {
    return Box._registry[id];
};

/**
 * Returns a registered Box from the registry by name
 * @param name
 * @returns {*}
 */
Box.getByName = function(name) {
    var id = Box._nameRegistry[name];
    return id ? Box._registry[id] : null;
};

/**
 * cleans up the Box.s_oRegistry
 */
Box.clean = function () {
    Box._id = 0;
    Box._registry = {};
};

/**
 * @param setup {Object} map of settings
 *
 * Schema: {
 *         [width] {Number|String}
 *         [height] {Number|String}
 *         [parent] {HTMLElement}
 *         [flow] {String}
 *     }
 *
 * @return {Box}
 */
api.createBox = function createBox(setup) {

    var config = setup || {};
    var box = new Box(
            config.width,
            config.height,
            (config.parent || config.container)
        )
        .setFlowDirection(config.flow)
        .setComponent(config.component);

    if (config.decorators) {
        config.decorators.forEach(function(decoratorName) {
            box.addDecorator(decoratorName);
        });
    }

    if (config.name) {
        box.setName(config.name);
    }

    if (config.className) {
        box.addClass(config.className);
    }

    return box;
};

/**
 * @param setup {Object} map of settings
 *
 * Schema: {
 *         [width] {Number|String}
 *         [height] {Number|String}
 *         [left] {Number|String}
 *         [right] {Number|String}
 *     }
 *
 * @return {Dialog}
 */
api.createDialog = function createDialog(setup) {

    setup = setup || {};

    return new Dialog(
        setup.width,
        setup.height,
        setup.left,
        setup.right
    );
};

}.call(this));


text:
layout: fluid/cli_docs_base
category: cli
id: cli-projects
page_name: Project Types
title: Project Types - Ionic CLI Documentation
hide_header_search: true
dark_header: true
---

{% comment %}
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
DO NOT MODIFY THIS FILE DIRECTLY -- IT IS GENERATED FROM THE CLI REPO
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
{% endcomment %}

# Project Types

{% include fluid/toc.html %}

The Ionic CLI works with a variety of Ionic project types. The type of a project is stored in the project's `ionic.config.json` file as `type`. Here is a list of project type values:

* `ionic-angular`: [Ionic Angular](#ionic-angular)
* `ionic1`: [Ionic 1](#ionic-1)
* `custom`: The CLI will not invoke anything for build or serve. See [Hooks](/docs/cli/configuring.html#hooks) to use `ionic build` and `ionic serve` with your own build process.

## Ionic Angular

Ionic Angular ([`ionic-angular`](https://www.npmjs.com/package/ionic-angular)) uses [Angular 5](https://angular.io/) and [`@ionic/app-scripts`](https://github.com/ionic-team/ionic-app-scripts) for tooling.

You can start a new Ionic Angular app with the following command:

```bash
$ ionic start --type=ionic-angular
```

See [Starter Templates](/docs/cli/starters.html#ionic-angular) for a list of starters for Ionic Angular.

Ionic Angular apps are written in [TypeScript](https://www.typescriptlang.org/) and [Sass](http://sass-lang.com/) and are compiled and built with [`@ionic/app-scripts`](https://github.com/ionic-team/ionic-app-scripts), which is a configurable build system optimized for Ionic Angular.

`ionic build` and `ionic serve` use `@ionic/app-scripts` out of the box, so it doesn't need to be invoked directly. It also ships with good defaults, but can be configured in a variety of ways. See [`README.md`](https://github.com/ionic-team/ionic-app-scripts/blob/master/README.md) for configuration details.

### Project Structure

```
project/
├─ ionic.config.json # Ionic project config file
├─ package.json
├─ src/
│  ├─ app/
│  │  ├─ app.component.ts # root component for your app
│  │  ├─ app.html # app component template
│  │  ├─ app.module.ts # NgModule for app component
│  │  ├─ app.scss # global SCSS
│  │  └─ main.ts # bootstrap file
│  ├─ assets/ # put your images, etc. here
│  ├─ pages/ # contains the page components for your app
│  ├─ theme/
│  │  └─ variables.scss # see https://ionicframework.com/docs/theming
│  └─ index.html # main html file
└─ www/ # build output directory
```
## Ionic 1

Ionic 1 ([`ionic-v1`](https://github.com/ionic-team/ionic-v1/)) uses [AngularJS](https://angularjs.org/).

You can start a new Ionic 1 app with the following command:

```bash
$ ionic start --type=ionic1
```

See [Starter Templates](/docs/cli/starters.html#ionic-1) for a list of starters for Ionic 1.

Out of the box, Ionic 1 apps have no build process. `www/index.html` includes the `www/css/style.css` file and the three provided JS files withing `www/js/`.

### Project Structure

```
project/
├─ bower.json
├─ gulpfile.js
├─ ionic.config.json # Ionic project config file
├─ package.json
├─ scss/
│  └─ ionic.app.scss # enable sass to use
└─ www/
   ├─ css/
   │  └─ style.css # vanilla CSS source file
   ├─ js/
   │  ├─ app.js # bootstrap file, contains `.config()`
   │  ├─ controllers.js # https://docs.angularjs.org/guide/controller
   │  └─ services.js # https://docs.angularjs.org/guide/services
   ├─ templates/ # AngularJS templates
   └─ index.html # main html file
```

### Enabling Sass

You can use [Sass](http://sass-lang.com/) by changing which CSS file `www/index.html` uses (`css/style.css` is the default, `css/ionic.app.css` is generated and includes both Ionic styles and your app's styles).

The main Sass source file is located at `scss/ionic.app.scss`.

If your `gulpfile.js` contains the `sass` task, the CLI will run it automatically during the `ionic build` and `ionic serve` commands.

redpajama_set_name: RedPajamaGithub


text:
function asyncComplete() {
  return new Promise((resolve) => {
    resolve('complete');
  });
}

// ----------------------------------------------------------------------------

(async function() {
  var value = await asyncComplete();
  assert.equal('complete', value);
  done();
})();


text:
var readline = require('readline'),
director = require('director'),
esl = require('modesl');

var Cli = exports.Cli = function(args, rdyCb) {
    this.rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        completer: this._completer.bind(this)
    });

    this.router = new director.cli.Router().configure({ notfound: this._onNotFound.bind(this) });
    var conn = this.conn = new esl.Connection(args.host, args.port, args.password, function(evt) {
        //subscribe to all events
        conn.subscribe(function() {
            if(rdyCb) rdyCb(evt);
        });
    });

    for(var i = 0, len = Cli.commands.length; i < len; ++i) {
        var cmd = Cli.commands[i];

        this.router.on(cmd[1], this[cmd[0].replace('/', 'slash_')].bind(this));
    }

    this.rl.setPrompt('$> ', 3);

    this.rl.on('line', this._onLine.bind(this));
    this.rl.on('close', this._onClose.bind(this));
    this.rl.on('SIGINT', this._onInt.bind(this));
    this.rl.on('SIGCONT', this._onCont.bind(this));

    this.conn.on('esl::event::command::reply', this._onEvent.bind(this));
    this.conn.on('esl::event::api::response', this._onEvent.bind(this));
    //this.conn.on('esl::event::**', this._onEvent.bind(this));
};

Cli.prototype.start = function() {
    this.rl.prompt();
};

//['/cmd', '/cmd :arg :arg']
Cli.commands = [
    ['/quit', '/quit'],         //quit the app
    ['/bye', '/bye'],           //quit the app
    ['/exit', '/exit'],         //quit the app
    ['/event', /\/event (\w+) (.+)/],       //enable events
    ['/noevents', '/noevents'], //disable all events previously enabled by /event
    ['/nixevent', /\/nixevent (.+)/],  //Enable all but one type of event
    //['/log', '/log :level'],           //set the loglevel of FreeSWITCH
    //['/nolog', '/nolog'],       //disable logging
    ['/uuid', '/uuid :uuid'],         //filter logs for a single call uuid
    //['/filter', '/filter'],
    ['/help', '/help'],     //display all fscli commands
    ['event', /event (\w+) (.+)/],
    ['api', /api (\w+) ?(\w+)?/],
    ['bgapi', /bgapi (\w+) ?(\w+)?/]
];

//Command handlers:
//-------------------
Cli.prototype.slash_quit = Cli.prototype.slash_bye = Cli.prototype.slash_exit = function() {
    this.rl.close();
};

Cli.prototype.slash_event = Cli.prototype.event = function(format, events) {
    this.conn.events(format, events);
};

Cli.prototype.slash_noevents = function() {
    this.conn.send('noevents');
};

Cli.prototype.slash_nixevent = function(events) {
    this.conn.send('nixevent ' + events);
};

Cli.prototype.slash_log = function(level) {
    this.conn.send('log ' + level);
};

Cli.prototype.slash_nolog = function() {
    this.conn.send('nolog');
};

Cli.prototype.slash_uuid = function(uuid) {
    this.conn.send('myevents ' + uuid);
};

Cli.prototype.slash_filter = function() {};

Cli.prototype.slash_help = function() {
    //display help
    console.log('Commands:');
    for(var i = 0, len = Cli.commands.length; i < len; ++i) {
        console.log(Cli.commands[i][0]);
    }
    this.rl.prompt();
};

Cli.prototype.api = function(cmd, arg) {
    this.conn.api(cmd, arg);
};

Cli.prototype.bgapi = function(cmd, arg) {
    this.conn.bgapi(cmd, arg, this._onEvent.bind(this));
};
//-------------------

Cli.prototype._onEvent = function(evt) {
    var txt = evt.getHeader('Reply-Text') || evt.getBody(),
    job = evt.getHeader('Job-UUID');

    if(txt.indexOf('Job-UUID') !== -1) {
        txt += ': ' + evt.getHeader('Job-UUID');
    }

    if(txt) {
        console.log(txt);
        this.rl.prompt();
    }
};

//Dispatch router when we get a line
Cli.prototype._onLine = function(line) {
    line = line.trim();

    if(line)
        this.router.dispatch('on', line.trim());
    else
        this.rl.prompt();
};

Cli.prototype._onNotFound = function() {
    console.log('Command not found!');
    this.rl.prompt();
};

//on readline close
Cli.prototype._onClose = function() {
    console.log('Good bye!');
    process.exit(0);
};

//on SIGINT (Control-C)
Cli.prototype._onInt = function() {
    console.log('Type /exit or /quit or /bye to exit.');
    this.rl.prompt();
};

//on SIGCONT (return from background)
Cli.prototype._onCont = function() {
    this.rl.prompt();
};

//on complete (Tab)
Cli.prototype._completer = function(line) {
    var completions = Cli.commands,
    hits = completions.filter(function(c) {
        return c[0].indexOf(line) === 0;
    });

    //returns [[matching, entries], originalSubstring]
    return [hits.length ? hits : completions, line]
};


text:
package net.afnf.and.twawm2;

import android.test.InstrumentationTestCase;

public class DexmakerInstrumentationTestCase extends InstrumentationTestCase {

	// MyInstrumentationTestRunnerに移動
}


text:
[![Build Status](https://travis-ci.org/sickill/rainbow.png?branch=master)](https://travis-ci.org/sickill/rainbow)
[![Code Climate](https://codeclimate.com/github/sickill/rainbow.png)](https://codeclimate.com/github/sickill/rainbow)
[![Coverage Status](https://coveralls.io/repos/sickill/rainbow/badge.png)](https://coveralls.io/r/sickill/rainbow)

Rainbow is a ruby gem for colorizing printed text on ANSI terminals.

It provides a string presenter object, which adds several methods to your
strings for wrapping them in [ANSI escape
codes](http://en.wikipedia.org/wiki/ANSI_escape_code). These codes when printed
in a terminal change text attributes like text color, background color,
intensity etc.

## Usage

To make your string colored wrap it with `Rainbow()` presenter and call
`.color(<color name>)` on it.

### Example

```ruby
require 'rainbow'

puts Rainbow("this is red").red + " and " + Rainbow("this on yellow bg").bg(:yellow) + " and " + Rainbow("even bright underlined!").underline.bright

# => "\e[31mthis is red\e[0m and \e[43mthis on yellow bg\e[0m and \e[4m\e[1meven bright underlined!\e[0m"
```

### Rainbow presenter API

Rainbow presenter adds the following methods to presented string:

* `color(c)` (with `foreground`, and `fg` aliases)
* `background(c)` (with `bg` alias)
* `bright`
* `underline`
* `blink`
* `inverse`
* `hide`
* `italic` (not well supported by terminal emulators).

Text color can also be changed by calling a method named by a color:

* `black`
* `red`
* `green`
* `yellow`
* `blue`
* `magenta`
* `cyan`
* `white`
* `aqua`
* `silver`
* `aliceblue`
* `indianred`

All of the methods return `self` (the presenter object) so you can chain method
calls:

```ruby
Rainbow("hola!").blue.bright.underline
```

### String mixin

If you don't like wrapping every string you want to colorize with `Rainbow()`
you can include all the rainbow presenter methods directly in a String class by
requiring `rainbow/ext/string`:

```ruby
require 'rainbow/ext/string'

puts "this is red".color(:red) + " and " + "this on yellow bg".background(:yellow) + " and " + "even bright underlined!".underline.bright
```

This way of using Rainbow is not recommended though as it pollutes String's
public interface with methods that are presentation specific.

NOTE: the mixin doesn't include shortcut methods for changing text color, you
should use "string".color(:blue) instead of "string".blue

NOTE: the mixin is included in String by default in rainbow 1.x versions.
In rainbow 2.x the behavior was changed - if you're upgrading from 1.x to 2.x
and you used direct String methods then you can either require the string
extension as shown above or update your code to use the new presenter API.

### Color specification

Both `color` and `background` accept color specified in any
of the following ways:

* ANSI color number (where 0 is black, 1 is red, 2 is green and so on):
  `Rainbow("hello").color(1)`

* [ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) name or [X11 color](https://en.wikipedia.org/wiki/X11_color_names) name as a symbol:
  `Rainbow("hello").color(:yellow)`.
  This can be simplified to `Rainbow("hello").yellow`

  See [Color list](#user-content-color-list) for all available color names.
  Note that ANSI colors can be changed in accordance with terminal setting.
  But X11 color is just a syntax sugar for RGB triplet. So you always see what you specified.

* RGB triplet as separate values in the range 0-255:
  `Rainbow("hello").color(115, 23, 98)`

* RGB triplet as a hex string:
  `Rainbow("hello").color("FFC482")` or `Rainbow("hello").color("#FFC482")`

When you specify a color with a RGB triplet rainbow finds the nearest match
from 256 colors palette. Note that it requires a 256-colors capable terminal to
display correctly.

### Configuration

Rainbow can be enabled/disabled globally by setting:

```ruby
Rainbow.enabled = true/false
```

When disabled all the methods return an unmodified string
(`Rainbow("hello").red == "hello"`).

It's enabled by default, unless STDOUT/STDERR is not a TTY or a terminal is
dumb.

### Advanced usage

`Rainbow()` and `Rainbow.enabled` operate on the global Rainbow wrapper
instance. If you would like to selectively enable/disable coloring in separate
parts of your application you can get a new Rainbow wrapper instance for each
of them and control the state of coloring during the runtime.

```ruby
rainbow_one = Rainbow.new
rainbow_two = Rainbow.new

rainbow_one.enabled = false

Rainbow("hello").red          # => "\e[31mhello\e[0m" ("hello" if not on TTY)
rainbow_one.wrap("hello").red # => "hello"
rainbow_two.wrap("hello").red # => "\e[31mhello\e[0m" ("hello" if not on TTY)
```

By default each new instance inherits enabled/disabled state from the global
`Rainbow.enabled`.

This feature comes handy for example when you have multiple output formatters
in your application and some of them print to a terminal but others write to a
file. Normally rainbow would detect that STDIN/STDERR is a TTY and would
colorize all the strings, even the ones that go through file writing
formatters. You can easily solve that by disabling coloring for the Rainbow
instances that are used by formatters with file output.

## Windows support

For Windows support, you should install the following gems:

```ruby
gem install windows-pr win32console
```

If the above gems aren't installed then all strings are returned unmodified.

## Installation

Add it to your Gemfile:

```ruby
gem 'rainbow'
```

Or just install it via rubygems:

```ruby
gem install rainbow
```

## Color list

### ANSI colors

* `black`
* `red`
* `green`
* `yellow`
* `blue`
* `magenta`
* `cyan`
* `white`

### X11 colors

* `aqua`
* `aquamarine`
* `mediumaquamarine`
* `azure`
* `beige`
* `bisque`
* `blanchedalmond`
* `darkblue`
* `lightblue`
* `mediumblue`
* `aliceblue`
* `cadetblue`
* `dodgerblue`
* `midnightblue`
* `navyblue`
* `powderblue`
* `royalblue`
* `skyblue`
* `deepskyblue`
* `lightskyblue`
* `slateblue`
* `darkslateblue`
* `mediumslateblue`
* `steelblue`
* `lightsteelblue`
* `brown`
* `rosybrown`
* `saddlebrown`
* `sandybrown`
* `burlywood`
* `chartreuse`
* `chocolate`
* `coral`
* `lightcoral`
* `cornflower`
* `cornsilk`
* `crimson`
* `darkcyan`
* `lightcyan`
* `firebrick`
* `fuchsia`
* `gainsboro`
* `gold`
* `goldenrod`
* `darkgoldenrod`
* `lightgoldenrod`
* `palegoldenrod`
* `gray`
* `darkgray`
* `dimgray`
* `lightgray`
* `slategray`
* `lightslategray`
* `webgray`
* `darkgreen`
* `lightgreen`
* `palegreen`
* `darkolivegreen`
* `yellowgreen`
* `forestgreen`
* `lawngreen`
* `limegreen`
* `seagreen`
* `darkseagreen`
* `lightseagreen`
* `mediumseagreen`
* `springgreen`
* `mediumspringgreen`
* `webgreen`
* `honeydew`
* `indianred`
* `indigo`
* `ivory`
* `khaki`
* `darkkhaki`
* `lavender`
* `lavenderblush`
* `lemonchiffon`
* `lime`
* `linen`
* `darkmagenta`
* `maroon`
* `webmaroon`
* `mintcream`
* `mistyrose`
* `moccasin`
* `oldlace`
* `olive`
* `olivedrab`
* `orange`
* `darkorange`
* `orchid`
* `darkorchid`
* `mediumorchid`
* `papayawhip`
* `peachpuff`
* `peru`
* `pink`
* `deeppink`
* `lightpink`
* `hotpink`
* `plum`
* `purple`
* `mediumpurple`
* `rebeccapurple`
* `webpurple`
* `darkred`
* `orangered`
* `mediumvioletred`
* `palevioletred`
* `salmon`
* `darksalmon`
* `lightsalmon`
* `seashell`
* `sienna`
* `silver`
* `darkslategray`
* `snow`
* `tan`
* `teal`
* `thistle`
* `tomato`
* `turquoise`
* `darkturquoise`
* `mediumturquoise`
* `paleturquoise`
* `violet`
* `darkviolet`
* `blueviolet`
* `wheat`
* `antiquewhite`
* `floralwhite`
* `ghostwhite`
* `navajowhite`
* `whitesmoke`
* `lightyellow`
* `greenyellow`

## Authors

[Marcin Kulik](http://ku1ik.com/) and [great open-source contributors](https://github.com/sickill/rainbow/graphs/contributors).


text:
package org.openur.remoting.client.ws.rs.security;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import javax.ws.rs.core.Application;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import org.openur.module.integration.security.shiro.OpenUrRdbmsRealm;
import org.openur.module.integration.security.shiro.testing.OpenUrRdbmsRealmMock;
import org.openur.remoting.resource.errorhandling.AuthenticationExceptionMapper;
import org.openur.remoting.resource.security.RdbmsRealmResource;

public class RdbmsRealmResourceClientTest
	extends JerseyTest
{
	private RdbmsRealmResourceClient realmClient;

	@Override
	protected Application configure()
	{
		// mocked service:
		OpenUrRdbmsRealm realmMock = new OpenUrRdbmsRealmMock();

		// Http-Testserver:
		AbstractBinder binder = new AbstractBinder()
		{
			@Override
			protected void configure()
			{
				bind(realmMock).to(OpenUrRdbmsRealm.class);
			}
		};

		ResourceConfig config = new ResourceConfig(RdbmsRealmResource.class)
				.register(binder);

		// Client:
		realmClient = new RdbmsRealmResourceClient("http://localhost:9998/");

		for (Class<?> provider : ((RdbmsRealmResourceClient) realmClient).getProviders())
		{
			config.register(provider);
		}

		config.register(AuthenticationExceptionMapper.class);

		return config;
	}

	@Test
	public void testGetName()
	{
		String result = realmClient.getName();
		System.out.println("Result: " + result);

		assertEquals(OpenUrRdbmsRealmMock.REALM_NAME, result);
	}

	@Test
	public void testSupports()
	{
		boolean b = realmClient.supports(OpenUrRdbmsRealmMock.USERNAME_PW_TOKEN);
		System.out.println("Result: " + b);
		assertTrue(b);

		b = realmClient.supports(OpenUrRdbmsRealmMock.TOKEN_WITH_WRONG_PW);
		System.out.println("Result: " + b);
		assertFalse(b);
	}

	@Test
	public void testGetAuthenticationInfo()
	{
		AuthenticationInfo info = realmClient.getAuthenticationInfo(OpenUrRdbmsRealmMock.USERNAME_PW_TOKEN);

		assertNotNull(info);
		System.out.println("Result: " + info);

		String passWord = new String((char[]) info.getCredentials());
		assertEquals(OpenUrRdbmsRealmMock.PASSWORD_1, passWord);

		String userName = info.getPrincipals().getPrimaryPrincipal().toString();
		assertEquals(OpenUrRdbmsRealmMock.USER_NAME_1, userName);

		byte[] saltBytes = ((SimpleAuthenticationInfo) info).getCredentialsSalt().getBytes();
		char[] chars = new char[saltBytes.length];
		for (int i = 0; i < saltBytes.length; i++)
		{
			chars[i] = (char) saltBytes[i];
		}
		assertEquals(OpenUrRdbmsRealmMock.SALT_BASE, new String(chars));
	}

	@Test(expected=AuthenticationException.class)
	public void testDoGetAuthenticationInfo_Wrong_PW()
	{
		realmClient.getAuthenticationInfo(OpenUrRdbmsRealmMock.TOKEN_WITH_WRONG_PW);
	}
}


text:
<?php

namespace ribris\qiwi;

use Yii;
use yii\web\Response;
use yii\web\XmlResponseFormatter;

/**
 * QIWI payment notify server
 */
class QiwiServer
{
    /**
     * @var array
     */
    private static $_notifyFields = [
        'bill_id',
        'status',
        'error',
        'amount',
        'user',
        'ccy',
        'comment'
    ];

    /**
     * @return array|bool
     */
    public static function request()
    {
        preg_match('#Basic\s([^;]+)#m', implode(';', $_SERVER), $basicToken);

        $token = base64_encode(
            Yii::$app->params['QIWI_SHOP_ID'] . ':' . Yii::$app->params['QIWI_NOTIFICATION_PWD']
        );

        if ($token === $basicToken[1]) {
            $result = [];
            foreach ($_POST as $k => $v) {
                if(in_array($k, self::$_notifyFields)) {
                    $result[$k] = $v;
                }
            }
            return $result;
        }
        return false;
    }

    /**
     * @param integer $returnCode
     */
    public static function response($returnCode = 0)
    {
        $response = new Response;
        $response->data = [$returnCode];
        $response->format = $response::FORMAT_XML;

        $response->formatters[$response::FORMAT_XML] = new XmlResponseFormatter;
        $response->formatters[$response::FORMAT_XML]->rootTag = 'result';
        $response->formatters[$response::FORMAT_XML]->itemTag = 'result_code';
        $response->formatters[$response::FORMAT_XML]->contentType = 'text/xml';

        $response->send();
        die;
    }

}


text:
describe('isCommand', function () {
  var isCommand = require('../lib/isCommand');

  beforeEach(function () {
    this.arguments = ['test-packages', '--arg', 'value'];
  })

  describe('when the first argument is the command', function () {
    it('returns true', function () {
      expect(isCommand(this.arguments, 'test-packages')).toBe(true);
    })
  })

  describe('when the first argument is not the command', function () {
    it('returns false', function () {
      expect(isCommand(this.arguments, 'something')).toBe(false);
    })
  })
})


text:
package seava.ad.presenter.ext.system.delegate;

import java.util.ArrayList;
import java.util.List;

import seava.j4e.api.Constants;
import seava.j4e.api.descriptor.IDsDefinition;
import seava.j4e.api.descriptor.IDsDefinitions;
import seava.j4e.api.descriptor.IFieldDefinition;
import seava.j4e.api.session.Session;
import seava.j4e.presenter.descriptor.DsDefinition;
import seava.j4e.presenter.service.AbstractPresenterDelegate;
import seava.ad.business.api.system.IDataSourceService;
import seava.ad.domain.impl.system.DataSource;
import seava.ad.domain.impl.system.DataSourceField;
import seava.ad.domain.impl.system.DataSourceRpc;
import seava.ad.presenter.impl.system.model.DataSource_Ds;

public class DataSource_Pd extends AbstractPresenterDelegate {

	/**
	 * Scan spring xml files to discover data-source definition and store them
	 * in database for easier access.
	 *
	 * @param filter
	 * @throws Exception
	 */

	public void synchronizeCatalog(DataSource_Ds filter) throws Exception {

		if (!Session.user.get().isSystemUser()) {
			throw new Exception(
					"This operation is allowed only for system users.");
		}

		IDataSourceService srv = (IDataSourceService) this
				.findEntityService(DataSource.class);

		List<DataSource> result = new ArrayList<DataSource>();

		if (this.getSettings().get(Constants.PROP_DEPLOYMENT)
				.equals(Constants.PROP_DEPLOYMENT_JEE)) {
			IDsDefinitions defs = this.getApplicationContext().getBean(
					IDsDefinitions.class);
			this._process(defs, result);
		} else {
			@SuppressWarnings("unchecked")
			List<IDsDefinitions> list = (List<IDsDefinitions>) this
					.getApplicationContext().getBean(
							Constants.SPRING_OSGI_DS_DEFINITIONS);
			for (IDsDefinitions defs : list) {
				this._process(defs, result);
			}
		}
		srv.update("delete from " + DataSourceField.class.getSimpleName(), null);
		srv.update("delete from " + DataSourceRpc.class.getSimpleName(), null);
		srv.update("delete from " + DataSource.class.getSimpleName(), null);
		srv.insert(result);
	}

	private void _process(IDsDefinitions defs, List<DataSource> result)
			throws Exception {
		for (IDsDefinition def : defs.getDsDefinitions()) {
			DataSource e = new DataSource();
			e.setName(def.getName());
			e.setModel(def.getModelClass().getCanonicalName());
			e.setActive(true);
			e.setIsAsgn(def.isAsgn());

			for (IFieldDefinition fld : ((DsDefinition) def).getModelFields()) {
				DataSourceField f = new DataSourceField();
				f.setName(fld.getName());
				f.setActive(true);
				f.setDataType(fld.getClassName());
				e.addToFields(f);
			}

			List<String> serviceMethods = def.getServiceMethods();
			if (serviceMethods != null) {
				for (String sm : serviceMethods) {
					DataSourceRpc sme = new DataSourceRpc();
					sme.setActive(true);
					sme.setDataSource(e);
					sme.setName(sm);
					e.addToServiceMethods(sme);
				}
			}
			result.add(e);
		}
	}
}


text:
int main( void )
{
  printf("cl_version.h standalone test PASSED.\n");
  return 0;
}


text: Using State Printer


text:
const CONFIG = {
    paths: [
        // fonts that should be compressed
        'assets/fonts/**/*'
    ]
};

const browserSync = require('browser-sync');

module.exports = function(gulp, plugins) {
    gulp.task('build:fonts', 'moves fonts to the build folder', function() {
        return gulp.src(CONFIG.paths, {base: gulp.inputPath})
            .pipe(plugins.newer(gulp.outputPath))
            .pipe(gulp.dest(gulp.outputPath))
            .pipe(browserSync.reload({stream: true}))
            .pipe(plugins.notify({message: 'Font compilation complete', onLast: true}));
    });

    gulp.task(
        'watch:fonts',
        'watches the source fonts for changes and moves them to the build folder when they do',
        ['build:fonts'], function() {
            gulp.watch(CONFIG.paths, ['build:fonts']);
        }
    );
};


text:
var CommentList = React.createClas({
    render: function () {
        return (
            <div className="commentList">
                <Comment author="test1">This is one comment</Comment>
                <Comment author="test2">This is another comment</Comment>
            </div>
            );
    }
});