<commit_before>/*
 * Screens.js - v0.9b
 * Copyright (C) 2013 Andreu Santaren Llop
 */

// Init ScreensJS library
{
    Array.prototype.last = function()
    {
        return this[this.length - 1];
    };

    Array.prototype.remove = function(index)
    {
        this.splice(index, 1);
    };

    window.BROADCAST_REGISTER_ARRAY = new Array();
    window.SCREEN_STACK = new Array();
}

// Create a class
function __CONTEXT_CLASS__(context, name, obj1, obj2)
{
    if (obj2 !== undefined)            // New class by heritance
    {
        if (typeof(obj1) !== "object")
        {
            throw "Extending from a non object";
        }

        // Clone the object
        var _asc_ = __CLONE__(obj1);

        // Get all element of obj and push it in _asc_
        for (var index in obj2)
        {
            var attr = obj2[index];
            _asc_[index] = attr;
        }

        // Init base properties
        _asc_.CLASS_TYPE.push(_asc_.CLASS_NAME);
        _asc_.CLASS_NAME = name;

        // Create the global variable for the class
        context[name] = _asc_;
        return _asc_;
    }
    else                        // New base class
    {
        // Init base methods
        obj1.New = function()
        {
            if (typeof(this.Super) !== 'undefined')
            {
                // Trying to create an object from an object, instead of a class
                return null;
            }

            var newObj = __CLONE__(this);

            newObj.OBJECT_UNIQUE_KEY = Math.floor(Math.random() * 10000000000000000).toString();

            if (newObj.CLASS_TYPE.length > 1)   // It is a subclass of something, create the Super
            {
                var baseClassName = newObj.CLASS_TYPE.last();

                var callname = '__CLONE__(' + baseClassName + ')';
                var parentObj = eval(callname);

                newObj.Super = parentObj;
            }
            else
            {
                newObj.Super = null;
            }

            // Call constructor
            newObj['Init'].apply(newObj, arguments);

            return newObj;
        };

        if (!('Init' in obj1))
        {
            obj1.Init = function() {};
        }

        // Init base properties
        obj1.CLASS_TYPE = new Array("__CLASS__");
        obj1.CLASS_NAME = name;

        // Create the global variable for the class
        context[name] = obj1;
        return obj1;
    }
}

// Create a class in the global context
function __CLASS__(name, obj1, obj2)
{
    return __CONTEXT_CLASS__(window, name, obj1, obj2);
}

// Base class
__CLASS__('Obj',
{
    Clone: function(obj)
    {
        return __CLONE__(obj);
    },

	Serialize: function(obj)
	{
		return __SERIALIZE__(obj);
	},

	Deserialize: function(obj)
	{
		return __DESERIALIZE__(obj);
	},

    LoadClass: function(name, baseurl, readyCallBack)
    {
        return __LOAD_CLASS__(name, baseurl, this, readyCallBack);
    },

    UnloadClass: function(classname)
    {
        return __UNLOAD_CLASS__(classname);
    },

	RegisterReceiver: function(delegate, filter)
    {
        return __REGISTER_RECEIVER__(this, delegate, filter);
    },

    UnregisterReceiver: function(receiver)
    {
        __UNREGISTER_RECEIVER__(receiver);
    },

    SendOrderedBroadcast: function(filter, message)
    {
        __SEND_BROADCAST__(filter, message, false);
    },

    SendBroadcast: function(filter, message)
    {
        __SEND_BROADCAST__(filter, message, true);
    }
});

// Base class for screens
__CLASS__('Screen', Obj,
{
    OnLoad: function()
    {},

    OnClose: function()
    {},

    OnReturn: function(retdata)
    {},

    CloseScreen: function(screen)
    {
        screen.OnClose();
    },

    PushScreen: function(selector, screen, loader, args)
    {
        __PUSH_SCREEN__(selector, screen, loader, args);
    },

    PopScreen: function(retdata)
    {
        __POP_SCREEN__(retdata);
    },

    SetScreen: function(selector, screen)
    {
        __SET_SCREEN__(selector, screen);
    },

    JQMLoader: function(pageSelector, args)
    {
        __JQM_LOADER__(pageSelector, args);
    },

    SetHtml: function(selector, html)
    {
	    __SET_HTML__(this, selector, html);
    },

    Brand: function(selector)
    {
	    __BRAND__(seletor, this);
    },

    Unbrand: function(selector)
    {
	    __UNBRAND__(selector);
    },

    Callback: function(callback)
    {
        return __CALLBACK__(this, callback);
    },

    Ref: function(selector)
    {
        return __REF__(this, selector);
    },

    Click: function(delegate, selector)
    {
        __CLICK__(this, delegate, selector);
    },

    ListClick: function(delegate, selector)
    {
        __LIST_CLICK__(this, delegate, selector);
    },

    Change: function(delegate, selector)
    {
        __CHANGE__(this, delegate, selector);
    },

    CheckboxClick: function(delegate, selector)
    {
        __CHECKER_CLICK__(this, delegate, selector, 'checkbox');
    },

    RadioClick: function(delegate, selector)
    {
        __CHECKER_CLICK__(this, delegate, selector, 'radio');
    },

    MouseEnter: function(delegate, selector)
    {
        __MOUSE_ENTER__(this, delegate, selector);
    },

    MouseLeave: function(delegate, selector)
    {
        __MOUSE_LEAVE__(this, delegate, selector);
    },

    MouseDown: function(delegate, selector)
    {
        __MOUSE_DOWN__(this, delegate, selector);
    },

    MouseUp: function(delegate, selector)
    {
        __MOUSE_UP__(this, delegate, selector);
    },

    MouseMove: function(delegate, selector)
    {
        __MOUSE_MOVE__(this, delegate, selector);
    }
});

// Clone an object
function __CLONE__(obj)
{
   return __DESERIALIZE__(__SERIALIZE__(obj));
}

// Convert a class object to string
function __SERIALIZE__(obj)
{
    var fooArray = new Array();
    var attrArray = new Array();

    // Find all functions and convert to string
    for (var attr in obj)
    {
        if (typeof(obj[attr]) === 'function')
        {
            fooArray.push(obj[attr].toString());
            attrArray.push(attr);
        }
    }

    // Obtain a copy of the object (ignoring functions)
    var json = JSON.stringify(obj);
    var copy = JSON.parse(json);

    // Replace the original functions by the strings
    for (var i = 0 ; i < fooArray.length ; i++)
    {
        copy[attrArray[i]] = '(' + fooArray[i] + ')';
    }

    // Add an array for function names
    copy.OBJ_FOO_NAMES = attrArray;

    var serialized = JSON.stringify(copy);

    return serialized;
}

// Convert a string to a class object
function __DESERIALIZE__(obj)
{
    var copy = JSON.parse(obj);

    if (typeof(copy.OBJ_FOO_NAMES) !== 'object')
    {
        throw 'Not a valid serialized object';
    }

    // Take function string and evaluate to obtain the originals
    for (var i = 0 ; i < copy.OBJ_FOO_NAMES.length ; i++)
    {
        var fooStr = copy[copy.OBJ_FOO_NAMES[i]];
        copy[copy.OBJ_FOO_NAMES[i]] = eval('(' + fooStr + ')');
    }

    delete copy.OBJ_FOO_NAMES;

    return copy;
}

function __PUSH_SCREEN__(selector, screen, loader, args)
{
    var name = screen.CLASS_NAME;

    // Create an instance of screen class and save it in the stack
    var callname = name + '.New()';
    var screenObj = eval(callname);

    __BRAND__(selector, screenObj);

    loader(selector, args);     // execute loader callback
    screenObj.OnLoad();         // Screen OnLoad methode

    // Add screen to stack
    window.SCREEN_STACK.push({screen: screenObj, baseurl: selector, loader: loader});
}

function __POP_SCREEN__(retdata)
{
    // It is the main screen, no one in the back
    if (window.SCREEN_STACK.length <= 1)
    {
        return;
    }

    // Close the current screen
    var lastScreen = window.SCREEN_STACK.pop();
    lastScreen.screen.OnClose();

    // Get de previus screen object
    var stackObj = window.SCREEN_STACK.last();

    var pageSelector = stackObj.baseurl;
    var lastPageSelector = lastScreen.baseurl;

    // Disable all events
    $(lastPageSelector).add("*").off();

    __UNBRAND__(lastScreen.screen);

    stackObj.loader(pageSelector);
    stackObj.screen.OnLoad();      // Screen OnLoad methode

    // Call the return function
    if (retdata !== null)
    {
        stackObj.screen.OnReturn(retdata);
    }
}

// Set a Screen class to control a part of an existing page
function __SET_SCREEN__(selector, screen)
{
    var name = screen.CLASS_NAME;

    // Disable all events
    $(selector).find("*").off();

    // Create an instance of screen class and save it in the stack
    var callname = name + '.New()';
    var screenObj = eval(callname);

    __BRAND__(selector, screenObj);

    screenObj.OnLoad();      // Screen OnLoad methode
}

function __JQM_LOADER__(pageSelector, args)
{
    $.mobile.changePage(pageSelector);
}

// Insert HTML in the DOM and update screen classes
function __SET_HTML__(screen, selector, html)
{
	__REF__(screen, selector).html(html);
    __BRAND__(selector, screen);
}

// Set the Screens brand for a piece of DOM
function __BRAND__(selector, screen)
{
	$(selector).attr('screensclass', screen.CLASS_NAME);
    $(selector).attr('screensid', screen.OBJECT_UNIQUE_KEY);
	$(selector).find('*').attr('screensclass', screen.CLASS_NAME);
    $(selector).find('*').attr('screensid', screen.OBJECT_UNIQUE_KEY);
}

// Remove the Screens brand
function __UNBRAND__(selector)
{
	$(selector).removeAttr('screensclass');
    $(selector).removeAttr('screensid');
	$(selector).find('*').removeAttr('screensclass');
    $(selector).find('*').removeAttr('screensid');
}

// Load a class
function __LOAD_CLASS__(name, baseurl, obj, readyCallBack)
{
    var jsurl = baseurl + "/" + name + ".js";

    if (typeof(window[name]) === 'undefined')
    {
        if (readyCallBack == null)
        {
            jQuery.ajaxSetup({async:false});

            // Load JavaScript class
            $.getScript(jsurl);

            jQuery.ajaxSetup({async:true});

            return true;
        }
        else
        {
            // Load JavaScript class
            $.getScript(jsurl, $.proxy(readyCallBack, obj));

            return true;
        }
    }
    else
    {
        // Class already loaded
        return false;
    }
}

function __UNLOAD_CLASS__(classname)
{
    if (typeof(classname) === 'string')
    {
        return delete window[classname];
    }
    else if (typeof(classname) === 'object')
    {
        return delete classname;
    }
    else
    {
        return false;
    }
}

// Callback in the obj context setting the original 'this' as argument
function __CALLBACK__(obj, callback)
{
    return function()
    {
        $.proxy(callback, obj)(this);
    };
}

// Get an element of a screen by a selector
function __REF__(obj, selector)
{
    return $(
    			"[screensclass='" + obj.CLASS_NAME + "']" +
    			"[screensid='" + obj.OBJECT_UNIQUE_KEY + "']" +
    			selector
    		);
}

// Set click event delegate
function __CLICK__(obj, delegate, selector)
{
    __REF__(obj, selector).click(function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set list click event delegate
function __LIST_CLICK__(obj, delegate, selector)
{
    __REF__(obj, selector).on('click', 'li', function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Element changed delegate
function __CHANGE__(obj, delegate, selector)
{
    __REF__(obj, selector).on('change', function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set checkbox/radio click event delegate
function __CHECKER_CLICK__(obj, delegate, selector, type)
{
	__REF__(obj, selector).find('input[type=' + type + ']').on('click', function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set mouse ter delegate
function __MOUSE_ENTER__(obj, delegate, selector)
{
    __REF__(obj, selector).mouseenter(function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set mouse leave delegate
function __MOUSE_LEAVE__(obj, delegate, selector)
{
    __REF__(obj, selector).mouseleave(function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set mouse down delegate
function __MOUSE_DOWN__(obj, delegate, selector)
{
    __REF__(obj, selector).mousedown(function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set mouse up delegate
function __MOUSE_UP__(obj, delegate, selector)
{
    __REF__(obj, selector).mouseup(function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set mouse move delegate
function __MOUSE_MOVE__(obj, delegate, selector)
{
    __REF__(obj, selector).mousemove(function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Register a broadcast receiver
function __REGISTER_RECEIVER__(obj, delegate, filter)
{
    var broadcastObj = {callback: $.proxy(delegate, obj), filter: filter, id: Math.random()};
    window.BROADCAST_REGISTER_ARRAY.push(broadcastObj);

    return broadcastObj.id;
}

// Unregister a broadcast receiver
function __UNREGISTER_RECEIVER__(receiver)
{
    for (var i = 0 ; i < window.BROADCAST_REGISTER_ARRAY.length ; i++)
    {
        if (window.BROADCAST_REGISTER_ARRAY[i].id === receiver)
        {
            window.BROADCAST_REGISTER_ARRAY.remove(i);
            return;
        }
    }
}

// Send broadcast message
function __SEND_BROADCAST__(filter, message, massive)
{
    // Make a copy of the array to avoid problems when others change it
    var arrCopy = window.BROADCAST_REGISTER_ARRAY.slice();

    for (var i = 0 ; i < arrCopy.length ; i++)
    {
        if (arrCopy[i].filter === filter)
        {
            if (massive)
            {
                arrCopy[i].callback(message);
            }
            else
            {
                // If ordered broadcast and callback returns true, halt broadcast
                if (arrCopy[i].callback(message)) return;
            }
        }
    }
}
<commit_msg>UnloadClass now accepts only an object as argument.<commit_after>/*
 * Screens.js - v0.9b
 * Copyright (C) 2013 Andreu Santaren Llop
 */

// Init ScreensJS library
{
    Array.prototype.last = function()
    {
        return this[this.length - 1];
    };

    Array.prototype.remove = function(index)
    {
        this.splice(index, 1);
    };

    window.BROADCAST_REGISTER_ARRAY = new Array();
    window.SCREEN_STACK = new Array();
}

// Create a class
function __CONTEXT_CLASS__(context, name, obj1, obj2)
{
    if (obj2 !== undefined)            // New class by heritance
    {
        if (typeof(obj1) !== "object")
        {
            throw "Extending from a non object";
        }

        // Clone the object
        var _asc_ = __CLONE__(obj1);

        // Get all element of obj and push it in _asc_
        for (var index in obj2)
        {
            var attr = obj2[index];
            _asc_[index] = attr;
        }

        // Init base properties
        _asc_.CLASS_TYPE.push(_asc_.CLASS_NAME);
        _asc_.CLASS_NAME = name;

        // Create the global variable for the class
        context[name] = _asc_;
        return _asc_;
    }
    else                        // New base class
    {
        // Init base methods
        obj1.New = function()
        {
            if (typeof(this.Super) !== 'undefined')
            {
                // Trying to create an object from an object, instead of a class
                return null;
            }

            var newObj = __CLONE__(this);

            newObj.OBJECT_UNIQUE_KEY = Math.floor(Math.random() * 10000000000000000).toString();

            if (newObj.CLASS_TYPE.length > 1)   // It is a subclass of something, create the Super
            {
                var baseClassName = newObj.CLASS_TYPE.last();

                var callname = '__CLONE__(' + baseClassName + ')';
                var parentObj = eval(callname);

                newObj.Super = parentObj;
            }
            else
            {
                newObj.Super = null;
            }

            // Call constructor
            newObj['Init'].apply(newObj, arguments);

            return newObj;
        };

        if (!('Init' in obj1))
        {
            obj1.Init = function() {};
        }

        // Init base properties
        obj1.CLASS_TYPE = new Array("__CLASS__");
        obj1.CLASS_NAME = name;

        // Create the global variable for the class
        context[name] = obj1;
        return obj1;
    }
}

// Create a class in the global context
function __CLASS__(name, obj1, obj2)
{
    return __CONTEXT_CLASS__(window, name, obj1, obj2);
}

// Base class
__CLASS__('Obj',
{
    Clone: function(obj)
    {
        return __CLONE__(obj);
    },

	Serialize: function(obj)
	{
		return __SERIALIZE__(obj);
	},

	Deserialize: function(obj)
	{
		return __DESERIALIZE__(obj);
	},

    LoadClass: function(name, baseurl, readyCallBack)
    {
        return __LOAD_CLASS__(name, baseurl, this, readyCallBack);
    },

    UnloadClass: function(classname)
    {
        return __UNLOAD_CLASS__(classname);
    },

	RegisterReceiver: function(delegate, filter)
    {
        return __REGISTER_RECEIVER__(this, delegate, filter);
    },

    UnregisterReceiver: function(receiver)
    {
        __UNREGISTER_RECEIVER__(receiver);
    },

    SendOrderedBroadcast: function(filter, message)
    {
        __SEND_BROADCAST__(filter, message, false);
    },

    SendBroadcast: function(filter, message)
    {
        __SEND_BROADCAST__(filter, message, true);
    }
});

// Base class for screens
__CLASS__('Screen', Obj,
{
    OnLoad: function()
    {},

    OnClose: function()
    {},

    OnReturn: function(retdata)
    {},

    CloseScreen: function(screen)
    {
        screen.OnClose();
    },

    PushScreen: function(selector, screen, loader, args)
    {
        __PUSH_SCREEN__(selector, screen, loader, args);
    },

    PopScreen: function(retdata)
    {
        __POP_SCREEN__(retdata);
    },

    SetScreen: function(selector, screen)
    {
        __SET_SCREEN__(selector, screen);
    },

    JQMLoader: function(pageSelector, args)
    {
        __JQM_LOADER__(pageSelector, args);
    },

    SetHtml: function(selector, html)
    {
	    __SET_HTML__(this, selector, html);
    },

    Brand: function(selector)
    {
	    __BRAND__(seletor, this);
    },

    Unbrand: function(selector)
    {
	    __UNBRAND__(selector);
    },

    Callback: function(callback)
    {
        return __CALLBACK__(this, callback);
    },

    Ref: function(selector)
    {
        return __REF__(this, selector);
    },

    Click: function(delegate, selector)
    {
        __CLICK__(this, delegate, selector);
    },

    ListClick: function(delegate, selector)
    {
        __LIST_CLICK__(this, delegate, selector);
    },

    Change: function(delegate, selector)
    {
        __CHANGE__(this, delegate, selector);
    },

    CheckboxClick: function(delegate, selector)
    {
        __CHECKER_CLICK__(this, delegate, selector, 'checkbox');
    },

    RadioClick: function(delegate, selector)
    {
        __CHECKER_CLICK__(this, delegate, selector, 'radio');
    },

    MouseEnter: function(delegate, selector)
    {
        __MOUSE_ENTER__(this, delegate, selector);
    },

    MouseLeave: function(delegate, selector)
    {
        __MOUSE_LEAVE__(this, delegate, selector);
    },

    MouseDown: function(delegate, selector)
    {
        __MOUSE_DOWN__(this, delegate, selector);
    },

    MouseUp: function(delegate, selector)
    {
        __MOUSE_UP__(this, delegate, selector);
    },

    MouseMove: function(delegate, selector)
    {
        __MOUSE_MOVE__(this, delegate, selector);
    }
});

// Clone an object
function __CLONE__(obj)
{
   return __DESERIALIZE__(__SERIALIZE__(obj));
}

// Convert a class object to string
function __SERIALIZE__(obj)
{
    var fooArray = new Array();
    var attrArray = new Array();

    // Find all functions and convert to string
    for (var attr in obj)
    {
        if (typeof(obj[attr]) === 'function')
        {
            fooArray.push(obj[attr].toString());
            attrArray.push(attr);
        }
    }

    // Obtain a copy of the object (ignoring functions)
    var json = JSON.stringify(obj);
    var copy = JSON.parse(json);

    // Replace the original functions by the strings
    for (var i = 0 ; i < fooArray.length ; i++)
    {
        copy[attrArray[i]] = '(' + fooArray[i] + ')';
    }

    // Add an array for function names
    copy.OBJ_FOO_NAMES = attrArray;

    var serialized = JSON.stringify(copy);

    return serialized;
}

// Convert a string to a class object
function __DESERIALIZE__(obj)
{
    var copy = JSON.parse(obj);

    if (typeof(copy.OBJ_FOO_NAMES) !== 'object')
    {
        throw 'Not a valid serialized object';
    }

    // Take function string and evaluate to obtain the originals
    for (var i = 0 ; i < copy.OBJ_FOO_NAMES.length ; i++)
    {
        var fooStr = copy[copy.OBJ_FOO_NAMES[i]];
        copy[copy.OBJ_FOO_NAMES[i]] = eval('(' + fooStr + ')');
    }

    delete copy.OBJ_FOO_NAMES;

    return copy;
}

function __PUSH_SCREEN__(selector, screen, loader, args)
{
    var name = screen.CLASS_NAME;

    // Create an instance of screen class and save it in the stack
    var callname = name + '.New()';
    var screenObj = eval(callname);

    __BRAND__(selector, screenObj);

    loader(selector, args);     // execute loader callback
    screenObj.OnLoad();         // Screen OnLoad methode

    // Add screen to stack
    window.SCREEN_STACK.push({screen: screenObj, baseurl: selector, loader: loader});
}

function __POP_SCREEN__(retdata)
{
    // It is the main screen, no one in the back
    if (window.SCREEN_STACK.length <= 1)
    {
        return;
    }

    // Close the current screen
    var lastScreen = window.SCREEN_STACK.pop();
    lastScreen.screen.OnClose();

    // Get de previus screen object
    var stackObj = window.SCREEN_STACK.last();

    var pageSelector = stackObj.baseurl;
    var lastPageSelector = lastScreen.baseurl;

    // Disable all events
    $(lastPageSelector).add("*").off();

    __UNBRAND__(lastScreen.screen);

    stackObj.loader(pageSelector);
    stackObj.screen.OnLoad();      // Screen OnLoad methode

    // Call the return function
    if (retdata !== null)
    {
        stackObj.screen.OnReturn(retdata);
    }
}

// Set a Screen class to control a part of an existing page
function __SET_SCREEN__(selector, screen)
{
    var name = screen.CLASS_NAME;

    // Disable all events
    $(selector).find("*").off();

    // Create an instance of screen class and save it in the stack
    var callname = name + '.New()';
    var screenObj = eval(callname);

    __BRAND__(selector, screenObj);

    screenObj.OnLoad();      // Screen OnLoad methode
}

function __JQM_LOADER__(pageSelector, args)
{
    $.mobile.changePage(pageSelector);
}

// Insert HTML in the DOM and update screen classes
function __SET_HTML__(screen, selector, html)
{
	__REF__(screen, selector).html(html);
    __BRAND__(selector, screen);
}

// Set the Screens brand for a piece of DOM
function __BRAND__(selector, screen)
{
	$(selector).attr('screensclass', screen.CLASS_NAME);
    $(selector).attr('screensid', screen.OBJECT_UNIQUE_KEY);
	$(selector).find('*').attr('screensclass', screen.CLASS_NAME);
    $(selector).find('*').attr('screensid', screen.OBJECT_UNIQUE_KEY);
}

// Remove the Screens brand
function __UNBRAND__(selector)
{
	$(selector).removeAttr('screensclass');
    $(selector).removeAttr('screensid');
	$(selector).find('*').removeAttr('screensclass');
    $(selector).find('*').removeAttr('screensid');
}

// Load a class
function __LOAD_CLASS__(name, baseurl, obj, readyCallBack)
{
    var jsurl = baseurl + "/" + name + ".js";

    if (typeof(window[name]) === 'undefined')
    {
        if (readyCallBack == null)
        {
            jQuery.ajaxSetup({async:false});

            // Load JavaScript class
            $.getScript(jsurl);

            jQuery.ajaxSetup({async:true});

            return true;
        }
        else
        {
            // Load JavaScript class
            $.getScript(jsurl, $.proxy(readyCallBack, obj));

            return true;
        }
    }
    else
    {
        // Class already loaded
        return false;
    }
}

function __UNLOAD_CLASS__(classname)
{
    if (typeof(classname) === 'object')
    {
        return delete classname;
    }
    else
    {
        return false;
    }
}

// Callback in the obj context setting the original 'this' as argument
function __CALLBACK__(obj, callback)
{
    return function()
    {
        $.proxy(callback, obj)(this);
    };
}

// Get an element of a screen by a selector
function __REF__(obj, selector)
{
    return $(
    			"[screensclass='" + obj.CLASS_NAME + "']" +
    			"[screensid='" + obj.OBJECT_UNIQUE_KEY + "']" +
    			selector
    		);
}

// Set click event delegate
function __CLICK__(obj, delegate, selector)
{
    __REF__(obj, selector).click(function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set list click event delegate
function __LIST_CLICK__(obj, delegate, selector)
{
    __REF__(obj, selector).on('click', 'li', function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Element changed delegate
function __CHANGE__(obj, delegate, selector)
{
    __REF__(obj, selector).on('change', function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set checkbox/radio click event delegate
function __CHECKER_CLICK__(obj, delegate, selector, type)
{
	__REF__(obj, selector).find('input[type=' + type + ']').on('click', function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set mouse ter delegate
function __MOUSE_ENTER__(obj, delegate, selector)
{
    __REF__(obj, selector).mouseenter(function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set mouse leave delegate
function __MOUSE_LEAVE__(obj, delegate, selector)
{
    __REF__(obj, selector).mouseleave(function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set mouse down delegate
function __MOUSE_DOWN__(obj, delegate, selector)
{
    __REF__(obj, selector).mousedown(function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set mouse up delegate
function __MOUSE_UP__(obj, delegate, selector)
{
    __REF__(obj, selector).mouseup(function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Set mouse move delegate
function __MOUSE_MOVE__(obj, delegate, selector)
{
    __REF__(obj, selector).mousemove(function()
    {
        $.proxy(delegate, obj)(this);
    });
}

// Register a broadcast receiver
function __REGISTER_RECEIVER__(obj, delegate, filter)
{
    var broadcastObj = {callback: $.proxy(delegate, obj), filter: filter, id: Math.random()};
    window.BROADCAST_REGISTER_ARRAY.push(broadcastObj);

    return broadcastObj.id;
}

// Unregister a broadcast receiver
function __UNREGISTER_RECEIVER__(receiver)
{
    for (var i = 0 ; i < window.BROADCAST_REGISTER_ARRAY.length ; i++)
    {
        if (window.BROADCAST_REGISTER_ARRAY[i].id === receiver)
        {
            window.BROADCAST_REGISTER_ARRAY.remove(i);
            return;
        }
    }
}

// Send broadcast message
function __SEND_BROADCAST__(filter, message, massive)
{
    // Make a copy of the array to avoid problems when others change it
    var arrCopy = window.BROADCAST_REGISTER_ARRAY.slice();

    for (var i = 0 ; i < arrCopy.length ; i++)
    {
        if (arrCopy[i].filter === filter)
        {
            if (massive)
            {
                arrCopy[i].callback(message);
            }
            else
            {
                // If ordered broadcast and callback returns true, halt broadcast
                if (arrCopy[i].callback(message)) return;
            }
        }
    }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Contains bde specific tasks
 */
module.exports = function (grunt) {

  grunt.registerTask('build', [
    'noflo_browser',
    'uglify:noflo'
  ]);

};
<commit_msg>"build" grunt task renamed to "+build" for show in default task<commit_after>'use strict';

/**
 * Contains bde specific tasks
 */
module.exports = function (grunt) {
  grunt.registerTask('+build', 'Built the noflo library.', [
    'noflo_browser',
    'uglify:noflo'
  ]);
};
<|endoftext|>


<commit_before>const postStatus = require('./../../api/twitter-api').postStatus;
const filterMentions = require('./filterMentions');
const countSyllables = require('./../lang/countSyllables');

const syllableRequest = (status_id, screen_name, text) => {
    text = filterMentions(text);
    let syllables = countSyllables(text);
    let message = `@${screen_name}\nSyllable Count: ${syllables.count}\nPhonemes: ${syllables.phonemes}`;

    let params = {
        in_reply_to_status_id: status_id,
        status: message
    };

    return postStatus(params);
};

module.exports = syllableRequest;<commit_msg>Remove phonemes in syllableRequest<commit_after>const postStatus = require('./../../api/twitter-api').postStatus;
const filterMentions = require('./filterMentions');
const countSyllables = require('./../lang/countSyllables');

const syllableRequest = (status_id, screen_name, text) => {
    text = filterMentions(text);
    let syllables = countSyllables(text);
    let message = `@${screen_name}\nSyllable Count: ${syllables.count}`;

    let params = {
        in_reply_to_status_id: status_id,
        status: message
    };

    return postStatus(params);
};

module.exports = syllableRequest;<|endoftext|>


<commit_before>var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var url = require('url');
var paths = require('./paths');
var getClientEnvironment = require('./env');
var StatsPlugin = require('stats-webpack-plugin');

function ensureSlash(path, needsSlash) {
  var hasSlash = path.endsWith('/');
  if (hasSlash && !needsSlash) {
    return path.substr(path, path.length - 1);
  } else if (!hasSlash && needsSlash) {
    return path + '/';
  } else {
    return path;
  }
}

// We use "homepage" field to infer "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
var homepagePath = require(paths.appPackageJson).homepage;
var homepagePathname = homepagePath ? url.parse(homepagePath).pathname : '/';
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
var publicPath = ensureSlash(homepagePathname, true);
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
var publicUrl = ensureSlash(homepagePathname, false);
// Get environment variables to inject into our app.
var env = getClientEnvironment(publicUrl);

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.');
}

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: 'source-map',
  // In production, we only want to load the polyfills and the app code.
  entry: {
    components: [
      require.resolve('./polyfills'),
      paths.appIndexJs,
    ],
  },
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: 'static/js/[name].[chunkhash:8].js',
    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We read `NODE_PATH` environment variable in `paths.js` and pass paths here.
    // We use `fallback` instead of `root` because we want `node_modules` to "win"
    // if there any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    fallback: paths.nodePaths,
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    extensions: ['.js', '.json', '.jsx', ''],
    alias: {
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web'
    }
  },

  module: {
    // First, run the linter.
    // It's important to do this before Babel processes the JS.
    preLoaders: [
      {
        test: /\.(js|jsx)$/,
        loader: 'eslint',
        include: paths.appSrc
      }
    ],
    loaders: [
      // Process JS with Babel.
      {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: 'babel',

      },
      // The notation here is somewhat confusing.
      // "postcss" loader applies autoprefixer to our CSS.
      // "css" loader resolves paths in CSS and adds assets as dependencies.
      // "style" loader normally turns CSS into JS modules injecting <style>,
      // but unlike in development configuration, we do something different.
      // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
      // (second argument), then grabs the result CSS and puts it into a
      // separate file in our build process. This way we actually ship
      // a single CSS file in production instead of JS code injecting <style>
      // tags. If you use code splitting, however, any async bundles will still
      // use the "style" loader inside the async code so CSS from them won't be
      // in the main CSS file.
      {
        test: /\.s?css$/,
        // "?-autoprefixer" disables autoprefixer in css-loader itself:
        // https://github.com/webpack/css-loader/issues/281
        // We already have it thanks to postcss. We only pass this flag in
        // production because "css" loader only enables autoprefixer-powered
        // removal of unnecessary prefixes when Uglify plugin is enabled.
        // Webpack 1.x uses Uglify plugin as a signal to minify *all* the assets
        // including CSS. This is confusing and will be removed in Webpack 2:
        // https://github.com/webpack/webpack/issues/283
        loader: ExtractTextPlugin.extract('style', 'css?importLoaders=1&-autoprefixer!postcss!sass')
        // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
      },
      // JSON is not enabled by default in Webpack but both Node and Browserify
      // allow it implicitly so we also enable it.
      {
        test: /\.json$/,
        loader: 'json'
      },
      // YAML
      {
        test: /\.yml$/,
        loader: 'json!yaml'
      },
      // "file" loader makes sure those assets end up in the `build` folder.
      // When you `import` an asset, you get its filename.
      {
        test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
        loader: 'file',
        query: {
          name: 'static/media/[name].[hash:8].[ext]'
        }
      },
      // "url" loader works just like "file" loader but it also embeds
      // assets smaller than specified size as data URLs to avoid requests.
      {
        test: /\.(mp4|webm|wav|mp3|m4a|aac|oga)(\?.*)?$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: 'static/media/[name].[hash:8].[ext]'
        }
      }
    ]
  },

  // We use PostCSS for autoprefixing only.
  postcss: function() {
    return [
      autoprefixer({
        browsers: [
          '>1%',
          'last 4 versions',
          'Firefox ESR',
          'not ie < 9', // React doesn't support IE8 anyway
        ]
      }),
    ];
  },
  plugins: [
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env),
    // This helps ensure the builds are consistent if source hasn't changed:
    new webpack.optimize.OccurrenceOrderPlugin(),
    // Try to dedupe duplicated modules, if any:
    new webpack.optimize.DedupePlugin(),
    // Minify the code.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        screw_ie8: true, // React doesn't support IE8
        warnings: false
      },
      mangle: {
        screw_ie8: true
      },
      output: {
        comments: false,
        screw_ie8: true
      }
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin('static/css/[name].[contenthash:8].css'),

    // Generate a manifest file which contains a mapping of all asset filenames
    // to their corresponding output file
    new StatsPlugin('manifest.json', {
      chunkModules: false,
      source: false,
      chunks: false,
      modules: false,
      assets: true
    }),
  ],
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  },
  externals: {
    jquery: 'jQuery',
  },
};
<commit_msg>[lint] `var` -> `const`<commit_after>const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const url = require('url');
const paths = require('./paths');
const getClientEnvironment = require('./env');
const StatsPlugin = require('stats-webpack-plugin');

function ensureSlash(path, needsSlash) {
  const hasSlash = path.endsWith('/');
  if (hasSlash && !needsSlash) {
    return path.substr(path, path.length - 1);
  } else if (!hasSlash && needsSlash) {
    return path + '/';
  } else {
    return path;
  }
}

// We use "homepage" field to infer "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
const homepagePath = require(paths.appPackageJson).homepage;
const homepagePathname = homepagePath ? url.parse(homepagePath).pathname : '/';
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = ensureSlash(homepagePathname, true);
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = ensureSlash(homepagePathname, false);
// Get environment constiables to inject into our app.
const env = getClientEnvironment(publicUrl);

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.');
}

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: 'source-map',
  // In production, we only want to load the polyfills and the app code.
  entry: {
    components: [
      require.resolve('./polyfills'),
      paths.appIndexJs,
    ],
  },
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: 'static/js/[name].[chunkhash:8].js',
    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We read `NODE_PATH` environment constiable in `paths.js` and pass paths here.
    // We use `fallback` instead of `root` because we want `node_modules` to "win"
    // if there any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    fallback: paths.nodePaths,
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    extensions: ['.js', '.json', '.jsx', ''],
    alias: {
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web'
    }
  },

  module: {
    // First, run the linter.
    // It's important to do this before Babel processes the JS.
    preLoaders: [
      {
        test: /\.(js|jsx)$/,
        loader: 'eslint',
        include: paths.appSrc
      }
    ],
    loaders: [
      // Process JS with Babel.
      {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: 'babel',

      },
      // The notation here is somewhat confusing.
      // "postcss" loader applies autoprefixer to our CSS.
      // "css" loader resolves paths in CSS and adds assets as dependencies.
      // "style" loader normally turns CSS into JS modules injecting <style>,
      // but unlike in development configuration, we do something different.
      // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
      // (second argument), then grabs the result CSS and puts it into a
      // separate file in our build process. This way we actually ship
      // a single CSS file in production instead of JS code injecting <style>
      // tags. If you use code splitting, however, any async bundles will still
      // use the "style" loader inside the async code so CSS from them won't be
      // in the main CSS file.
      {
        test: /\.s?css$/,
        // "?-autoprefixer" disables autoprefixer in css-loader itself:
        // https://github.com/webpack/css-loader/issues/281
        // We already have it thanks to postcss. We only pass this flag in
        // production because "css" loader only enables autoprefixer-powered
        // removal of unnecessary prefixes when Uglify plugin is enabled.
        // Webpack 1.x uses Uglify plugin as a signal to minify *all* the assets
        // including CSS. This is confusing and will be removed in Webpack 2:
        // https://github.com/webpack/webpack/issues/283
        loader: ExtractTextPlugin.extract('style', 'css?importLoaders=1&-autoprefixer!postcss!sass')
        // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
      },
      // JSON is not enabled by default in Webpack but both Node and Browserify
      // allow it implicitly so we also enable it.
      {
        test: /\.json$/,
        loader: 'json'
      },
      // YAML
      {
        test: /\.yml$/,
        loader: 'json!yaml'
      },
      // "file" loader makes sure those assets end up in the `build` folder.
      // When you `import` an asset, you get its filename.
      {
        test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
        loader: 'file',
        query: {
          name: 'static/media/[name].[hash:8].[ext]'
        }
      },
      // "url" loader works just like "file" loader but it also embeds
      // assets smaller than specified size as data URLs to avoid requests.
      {
        test: /\.(mp4|webm|wav|mp3|m4a|aac|oga)(\?.*)?$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: 'static/media/[name].[hash:8].[ext]'
        }
      }
    ]
  },

  // We use PostCSS for autoprefixing only.
  postcss: function() {
    return [
      autoprefixer({
        browsers: [
          '>1%',
          'last 4 versions',
          'Firefox ESR',
          'not ie < 9', // React doesn't support IE8 anyway
        ]
      }),
    ];
  },
  plugins: [
    // Makes some environment constiables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env),
    // This helps ensure the builds are consistent if source hasn't changed:
    new webpack.optimize.OccurrenceOrderPlugin(),
    // Try to dedupe duplicated modules, if any:
    new webpack.optimize.DedupePlugin(),
    // Minify the code.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        screw_ie8: true, // React doesn't support IE8
        warnings: false
      },
      mangle: {
        screw_ie8: true
      },
      output: {
        comments: false,
        screw_ie8: true
      }
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin('static/css/[name].[contenthash:8].css'),

    // Generate a manifest file which contains a mapping of all asset filenames
    // to their corresponding output file
    new StatsPlugin('manifest.json', {
      chunkModules: false,
      source: false,
      chunks: false,
      modules: false,
      assets: true
    }),
  ],
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  },
  externals: {
    jquery: 'jQuery',
  },
};
<|endoftext|>


<commit_before>/**
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author bhouston / http://exocortex.com
 */

THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {

	this.elements = new Float32Array(9);

	this.set(

		( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
		n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
		n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1

	);
};

THREE.Matrix3.prototype = {

	constructor: THREE.Matrix3,

	set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {

		var te = this.elements;

		te[0] = n11; te[3] = n12; te[6] = n13;
		te[1] = n21; te[4] = n22; te[7] = n23;
		te[2] = n31; te[5] = n32; te[8] = n33;

		return this;

	},

	identity: function () {

		this.set(

			1, 0, 0,
			0, 1, 0,
			0, 0, 1

		);

		return this;

	},

	copy: function ( m ) {

		var me = m.elements;

		this.set(

			me[0], me[3], me[6],
			me[1], me[4], me[7],
			me[2], me[5], me[8]

		);

		return this;

	},

	multiplyVector3: function ( vector ) {

		console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
		return vector.applyMatrix3( this );

	},

	multiplyVector3Array: function ( a ) {

		console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
		return this.applyToVector3Array( a );

	},

	applyToVector3Array: function() {

		var v1 = new THREE.Vector3();

		return function ( a ) {

			for ( var i = 0, il = a.length; i < il; i += 3 ) {

				v1.x = a[ i ];
				v1.y = a[ i + 1 ];
				v1.z = a[ i + 2 ];

				v1.applyMatrix3( this );

				a[ i ]     = v1.x;
				a[ i + 1 ] = v1.y;
				a[ i + 2 ] = v1.z;

			}

			return a;

		};

	}(),

	multiplyScalar: function ( s ) {

		var te = this.elements;

		te[0] *= s; te[3] *= s; te[6] *= s;
		te[1] *= s; te[4] *= s; te[7] *= s;
		te[2] *= s; te[5] *= s; te[8] *= s;

		return this;

	},

	determinant: function () {

		var te = this.elements;

		var a = te[0], b = te[1], c = te[2],
			d = te[3], e = te[4], f = te[5],
			g = te[6], h = te[7], i = te[8];

		return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;

	},

	getInverse: function ( matrix, throwOnInvertible ) {

		// input: THREE.Matrix4
		// ( based on http://code.google.com/p/webgl-mjs/ )

		var me = matrix.elements;
		var te = this.elements;

		te[ 0 ] =   me[10] * me[5] - me[6] * me[9];
		te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
		te[ 2 ] =   me[6] * me[1] - me[2] * me[5];
		te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
		te[ 4 ] =   me[10] * me[0] - me[2] * me[8];
		te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
		te[ 6 ] =   me[9] * me[4] - me[5] * me[8];
		te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
		te[ 8 ] =   me[5] * me[0] - me[1] * me[4];

		var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];

		// no inverse

		if ( det === 0 ) {

			var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";

			if ( throwOnInvertible || false ) {

				throw new Error( msg );

			} else {

				console.warn( msg );

			}

			this.identity();

			return this;

		}

		this.multiplyScalar( 1.0 / det );

		return this;

	},

	transpose: function () {

		var tmp, m = this.elements;

		tmp = m[1]; m[1] = m[3]; m[3] = tmp;
		tmp = m[2]; m[2] = m[6]; m[6] = tmp;
		tmp = m[5]; m[5] = m[7]; m[7] = tmp;

		return this;

	},

	flattenToArrayOffset: function( array, offset ) {

		var te = this.elements;

		array[ offset     ] = te[0];
		array[ offset + 1 ] = te[1];
		array[ offset + 2 ] = te[2];

		array[ offset + 3 ] = te[3];
		array[ offset + 4 ] = te[4];
		array[ offset + 5 ] = te[5];

		array[ offset + 6 ] = te[6];
		array[ offset + 7 ] = te[7];
		array[ offset + 8 ]  = te[8];

		return array;

	},

	getNormalMatrix: function ( m ) {

		// input: THREE.Matrix4

		this.getInverse( m ).transpose();

		return this;

	},

	transposeIntoArray: function ( r ) {

		var m = this.elements;

		r[ 0 ] = m[ 0 ];
		r[ 1 ] = m[ 3 ];
		r[ 2 ] = m[ 6 ];
		r[ 3 ] = m[ 1 ];
		r[ 4 ] = m[ 4 ];
		r[ 5 ] = m[ 7 ];
		r[ 6 ] = m[ 2 ];
		r[ 7 ] = m[ 5 ];
		r[ 8 ] = m[ 8 ];

		return this;

	},

	fromArray: function ( array ) {

		this.elements.set( array );

		return this;

	},

	toArray: function () {

		var te = this.elements;

		return [
			te[ 0 ], te[ 1 ], te[ 2 ],
			te[ 3 ], te[ 4 ], te[ 5 ],
			te[ 6 ], te[ 7 ], te[ 8 ]
		];

	},

	clone: function () {

		var te = this.elements;

		return new THREE.Matrix3(

			te[0], te[3], te[6],
			te[1], te[4], te[7],
			te[2], te[5], te[8]

		);

	}

};
<commit_msg>Matrix3: Copy Matrix4 constructor style.<commit_after>/**
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author bhouston / http://exocortex.com
 */

THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {

	this.elements = new Float32Array( 9 );

	var te = this.elements;

	te[0] = ( n11 !== undefined ) ? n11 : 1; te[3] = n12 || 0; te[6] = n13 || 0;
	te[1] = n21 || 0; te[4] = ( n22 !== undefined ) ? n22 : 1; te[7] = n23 || 0;
	te[2] = n31 || 0; te[5] = n32 || 0; te[8] = ( n33 !== undefined ) ? n33 : 1;

};

THREE.Matrix3.prototype = {

	constructor: THREE.Matrix3,

	set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {

		var te = this.elements;

		te[0] = n11; te[3] = n12; te[6] = n13;
		te[1] = n21; te[4] = n22; te[7] = n23;
		te[2] = n31; te[5] = n32; te[8] = n33;

		return this;

	},

	identity: function () {

		this.set(

			1, 0, 0,
			0, 1, 0,
			0, 0, 1

		);

		return this;

	},

	copy: function ( m ) {

		var me = m.elements;

		this.set(

			me[0], me[3], me[6],
			me[1], me[4], me[7],
			me[2], me[5], me[8]

		);

		return this;

	},

	multiplyVector3: function ( vector ) {

		console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
		return vector.applyMatrix3( this );

	},

	multiplyVector3Array: function ( a ) {

		console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
		return this.applyToVector3Array( a );

	},

	applyToVector3Array: function() {

		var v1 = new THREE.Vector3();

		return function ( a ) {

			for ( var i = 0, il = a.length; i < il; i += 3 ) {

				v1.x = a[ i ];
				v1.y = a[ i + 1 ];
				v1.z = a[ i + 2 ];

				v1.applyMatrix3( this );

				a[ i ]     = v1.x;
				a[ i + 1 ] = v1.y;
				a[ i + 2 ] = v1.z;

			}

			return a;

		};

	}(),

	multiplyScalar: function ( s ) {

		var te = this.elements;

		te[0] *= s; te[3] *= s; te[6] *= s;
		te[1] *= s; te[4] *= s; te[7] *= s;
		te[2] *= s; te[5] *= s; te[8] *= s;

		return this;

	},

	determinant: function () {

		var te = this.elements;

		var a = te[0], b = te[1], c = te[2],
			d = te[3], e = te[4], f = te[5],
			g = te[6], h = te[7], i = te[8];

		return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;

	},

	getInverse: function ( matrix, throwOnInvertible ) {

		// input: THREE.Matrix4
		// ( based on http://code.google.com/p/webgl-mjs/ )

		var me = matrix.elements;
		var te = this.elements;

		te[ 0 ] =   me[10] * me[5] - me[6] * me[9];
		te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
		te[ 2 ] =   me[6] * me[1] - me[2] * me[5];
		te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
		te[ 4 ] =   me[10] * me[0] - me[2] * me[8];
		te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
		te[ 6 ] =   me[9] * me[4] - me[5] * me[8];
		te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
		te[ 8 ] =   me[5] * me[0] - me[1] * me[4];

		var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];

		// no inverse

		if ( det === 0 ) {

			var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";

			if ( throwOnInvertible || false ) {

				throw new Error( msg );

			} else {

				console.warn( msg );

			}

			this.identity();

			return this;

		}

		this.multiplyScalar( 1.0 / det );

		return this;

	},

	transpose: function () {

		var tmp, m = this.elements;

		tmp = m[1]; m[1] = m[3]; m[3] = tmp;
		tmp = m[2]; m[2] = m[6]; m[6] = tmp;
		tmp = m[5]; m[5] = m[7]; m[7] = tmp;

		return this;

	},

	flattenToArrayOffset: function( array, offset ) {

		var te = this.elements;

		array[ offset     ] = te[0];
		array[ offset + 1 ] = te[1];
		array[ offset + 2 ] = te[2];

		array[ offset + 3 ] = te[3];
		array[ offset + 4 ] = te[4];
		array[ offset + 5 ] = te[5];

		array[ offset + 6 ] = te[6];
		array[ offset + 7 ] = te[7];
		array[ offset + 8 ]  = te[8];

		return array;

	},

	getNormalMatrix: function ( m ) {

		// input: THREE.Matrix4

		this.getInverse( m ).transpose();

		return this;

	},

	transposeIntoArray: function ( r ) {

		var m = this.elements;

		r[ 0 ] = m[ 0 ];
		r[ 1 ] = m[ 3 ];
		r[ 2 ] = m[ 6 ];
		r[ 3 ] = m[ 1 ];
		r[ 4 ] = m[ 4 ];
		r[ 5 ] = m[ 7 ];
		r[ 6 ] = m[ 2 ];
		r[ 7 ] = m[ 5 ];
		r[ 8 ] = m[ 8 ];

		return this;

	},

	fromArray: function ( array ) {

		this.elements.set( array );

		return this;

	},

	toArray: function () {

		var te = this.elements;

		return [
			te[ 0 ], te[ 1 ], te[ 2 ],
			te[ 3 ], te[ 4 ], te[ 5 ],
			te[ 6 ], te[ 7 ], te[ 8 ]
		];

	},

	clone: function () {

		var te = this.elements;

		return new THREE.Matrix3(

			te[0], te[3], te[6],
			te[1], te[4], te[7],
			te[2], te[5], te[8]

		);

	}

};
<|endoftext|>


<commit_before>$(function() {

	$(".dropdownLowest").click(function(e) {
		e.preventDefault();
		$("#dph").val("10");
	});

	$(".dropdownLow").click(function(e) {
		e.preventDefault();
		$("#dph").val("15");
	});

	$(".dropdownNormal").click(function(e) {
		e.preventDefault();
		$("#dph").val("21");
	});

	$(".clear").click(function(e) {
		e.preventDefault();
		$("#dph").val("21");
		$("#cenaBezDph").val("");
		$("#cenaSDph").val("");
		$("#castkaDph").val("");
		$("#name").val("");
		$(".save").css("display", "none");
		$("#cenaBezDph").prop("disabled", false);
		$("#cenaSDph").prop("disabled", false);
	});

	$("#cenaBezDph").keyup(function() {
		if($(this).val()) {
			$("#cenaSDph").prop("disabled", true);
		} else {
			$("#cenaSDph").prop("disabled", false);
		}
	});

	$("#cenaSDph").keyup(function() {
		if($(this).val()) {
			$("#cenaBezDph").prop("disabled", true);
		} else {
			$("#cenaBezDph").prop("disabled", false);
		}
	});

	$(".run").click(function(e) {
		e.preventDefault();
		var inputTextDph = $("#dph");
		var inputTextCenaBezDph = $("#cenaBezDph");
		var inputTextCenaSDph = $("#cenaSDph");
		var inputTextCastkaDph = $("#castkaDph");
		var valDph = parseFloat(inputTextDph.val());
		var valCenaBezDph = parseFloat(parseFloat(inputTextCenaBezDph.val().replace(",", ".")).toFixed(2));
		var valCenaSDph = parseFloat(parseFloat(inputTextCenaSDph.val().replace(",", ".")).toFixed(2));
		var valCastkaDph = parseFloat(parseFloat(inputTextCastkaDph.val()).toFixed(2));
		if(!valCenaBezDph && !valCenaSDph) {
			return;
		}
		if($("#cenaSDph").prop("disabled")) {
			var castkaDph = parseFloat((valCenaBezDph * valDph / 100).toFixed(2));
			inputTextCastkaDph.val(castkaDph);
			inputTextCenaSDph.val((valCenaBezDph + castkaDph).toFixed(2));
		}
		else if($("#cenaBezDph").prop("disabled")) {
			// http://www.zakonyprolidi.cz/cs/2004-235#p37-2
			var koeficient = parseFloat((valDph / (valDph + 100)).toFixed(4));
			var castkaDph = parseFloat((valCenaSDph * koeficient).toFixed(2));
			var castkaSDph = parseFloat((valCenaSDph - castkaDph).toFixed(2));
			inputTextCastkaDph.val(castkaDph);
			inputTextCenaBezDph.val(castkaSDph);
		}

		$(".save").css("display", "inline");
	});

	$(".save").click(function(e) {
		e.preventDefault();
		$('#saveDialog').modal();
	});

	/*
	 * autofocus in modal dialog
	 */
	$('#saveDialog').on('shown.bs.modal', function () {
		$("#name").focus();
	})

    var dataTable = $('#items').DataTable({
    	"language" : {"url": "//cdn.datatables.net/plug-ins/f2c75b7247b/i18n/Czech.json"},
    	"ajax" : "/items",
    	"columns" : [ {"data" : "id"}, {"data": "name"}, {"data": "dph", "width": "30px"}, {"data": "cenaBezDph", "width" : "60px"}, {"data": "cenaSDph", "width" : "60px"}, {"data": "", "width" : "90px"} ],
    	"columnDefs" : [ {
			"targets": -1,
			"data": null,
			"defaultContent": "<button class='btn btn-primary btnNacist'>Načíst</button> <button class='btn btn-danger btnSmazat'>X</button> "
    	}, {
			"targets": 0,
			"visible": false
    	} ]
	});

    $('#items tbody').on( 'click', '.btnNacist', function () {
        var data = dataTable.row( $(this).parents('tr') ).data();
        var itemId = data.id;
        $.get("/items/" + itemId, function (data) {
        	$("#dph").val(data.dph);
        	$("#cenaBezDph").val(data.cenaBezDph);
        	$("#cenaSDph").val(data.cenaSDph);
        	$("#castkaDph").val(data.castkaDph);
        	$("#name").val(data.name);
        	if(data.cenaBezDphDisabled) {
        		$("#cenaBezDph").prop("disabled", true);
        		$("#cenaSDph").prop("disabled", false);
        	}
        	if(data.cenaSDphDisabled) {
        		$("#cenaBezDph").prop("disabled", false);
        		$("#cenaSDph").prop("disabled", true);
        	}
        });
    } );

    $(".saveConfirm").click(function(e) {
		e.preventDefault();
		var form = $("#submitForm");
		if(!form.valid()) {
			return;
		}
		var valName = $("#name").val();
		var valCenaBezDph = $("#cenaBezDph").val();
		var valCenaSDph = $("#cenaSDph").val();
		var valDph = $("#dph").val();
		var valCastkaDph = $("#castkaDph").val();
		var valCenaBezDphDisabled = $("#cenaBezDph").prop("disabled");
		var valCenaSDphDisabled = $("#cenaSDph").prop("disabled");
		$.post("/save", {name : valName, cenaBezDph : valCenaBezDph, cenaSDph : valCenaSDph,
						 dph : valDph, cenaBezDphDisabled : valCenaBezDphDisabled,
						 cenaSDphDisabled : valCenaSDphDisabled, castkaDph : valCastkaDph}, function(data) {
		});
		$('#saveDialog').modal("hide");
	});

    $('#name').keypress(function (e) {
    	 var key = e.which;
    	 if(key == 13)  // the enter key code
    	  {
    	    $('.saveConfirm').click();
    	    return false;
    	  }
	});

    $.validator.messages.required = "Toto pole je povinné!";

    $("#submitForm").validate(
    		{
    			rules: {
    				name: {
    					required : true,
    					minlength : 1
    				}
    			},
    			highlight: function(element) {
    				$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    			},
    			unhighlight: function(element) {
    				$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
    			}
    		}
    );

});<commit_msg>code cleanup<commit_after>$(function() {

	$(".dropdownLowest").click(function(e) {
		e.preventDefault();
		$("#dph").val("10");
	});

	$(".dropdownLow").click(function(e) {
		e.preventDefault();
		$("#dph").val("15");
	});

	$(".dropdownNormal").click(function(e) {
		e.preventDefault();
		$("#dph").val("21");
	});

	$(".clear").click(function(e) {
		e.preventDefault();
		$("#dph").val("21");
		$("#cenaBezDph").val("");
		$("#cenaSDph").val("");
		$("#castkaDph").val("");
		$("#name").val("");
		$(".save").css("display", "none");
		$("#cenaBezDph").prop("disabled", false);
		$("#cenaSDph").prop("disabled", false);
	});

	$("#cenaBezDph").keyup(function() {
		if($(this).val()) {
			$("#cenaSDph").prop("disabled", true);
		} else {
			$("#cenaSDph").prop("disabled", false);
		}
	});

	$("#cenaSDph").keyup(function() {
		if($(this).val()) {
			$("#cenaBezDph").prop("disabled", true);
		} else {
			$("#cenaBezDph").prop("disabled", false);
		}
	});

	$(".run").click(function(e) {
		e.preventDefault();
		var inputTextDph = $("#dph");
		var inputTextCenaBezDph = $("#cenaBezDph");
		var inputTextCenaSDph = $("#cenaSDph");
		var inputTextCastkaDph = $("#castkaDph");
		var valDph = parseFloat(inputTextDph.val());
		var valCenaBezDph = parseFloat(parseFloat(inputTextCenaBezDph.val().replace(",", ".")).toFixed(2));
		var valCenaSDph = parseFloat(parseFloat(inputTextCenaSDph.val().replace(",", ".")).toFixed(2));
		var valCastkaDph = parseFloat(parseFloat(inputTextCastkaDph.val()).toFixed(2));
		if(!valCenaBezDph && !valCenaSDph) {
			return;
		}
		if($("#cenaSDph").prop("disabled")) {
			var castkaDph = parseFloat((valCenaBezDph * valDph / 100).toFixed(2));
			inputTextCastkaDph.val(castkaDph);
			inputTextCenaSDph.val((valCenaBezDph + castkaDph).toFixed(2));
		}
		else if($("#cenaBezDph").prop("disabled")) {
			// http://www.zakonyprolidi.cz/cs/2004-235#p37-2
			var koeficient = parseFloat((valDph / (valDph + 100)).toFixed(4));
			var castkaDph = parseFloat((valCenaSDph * koeficient).toFixed(2));
			var castkaSDph = parseFloat((valCenaSDph - castkaDph).toFixed(2));
			inputTextCastkaDph.val(castkaDph);
			inputTextCenaBezDph.val(castkaSDph);
		}

		$(".save").css("display", "inline");
	});

	$(".save").click(function(e) {
		e.preventDefault();
		$('#saveDialog').modal();
	});

	/*
	 * autofocus in modal dialog
	 */
	$('#saveDialog').on('shown.bs.modal', function () {
		$("#name").focus();
	})

    var dataTable = $('#items').DataTable({
    	"language" : {"url": "//cdn.datatables.net/plug-ins/f2c75b7247b/i18n/Czech.json"},
    	"ajax" : "/items",
    	"columns" : [ {"data" : "id"}, {"data": "name"}, {"data": "dph", "width": "30px"}, {"data": "cenaBezDph", "width" : "60px"}, {"data": "cenaSDph", "width" : "60px"}, {"data": "", "width" : "90px"} ],
    	"columnDefs" : [ {
			"targets": -1,
			"data": null,
			"defaultContent": "<button class='btn btn-primary btnNacist'>Načíst</button>"
    	}, {
			"targets": 0,
			"visible": false
    	} ]
	});

    $('#items tbody').on( 'click', '.btnNacist', function () {
        var data = dataTable.row( $(this).parents('tr') ).data();
        var itemId = data.id;
        $.get("/items/" + itemId, function (data) {
        	$("#dph").val(data.dph);
        	$("#cenaBezDph").val(data.cenaBezDph);
        	$("#cenaSDph").val(data.cenaSDph);
        	$("#castkaDph").val(data.castkaDph);
        	$("#name").val(data.name);
        	if(data.cenaBezDphDisabled) {
        		$("#cenaBezDph").prop("disabled", true);
        		$("#cenaSDph").prop("disabled", false);
        	}
        	if(data.cenaSDphDisabled) {
        		$("#cenaBezDph").prop("disabled", false);
        		$("#cenaSDph").prop("disabled", true);
        	}
        });
    } );

    $(".saveConfirm").click(function(e) {
		e.preventDefault();
		var form = $("#submitForm");
		if(!form.valid()) {
			return;
		}
		var valName = $("#name").val();
		var valCenaBezDph = $("#cenaBezDph").val();
		var valCenaSDph = $("#cenaSDph").val();
		var valDph = $("#dph").val();
		var valCastkaDph = $("#castkaDph").val();
		var valCenaBezDphDisabled = $("#cenaBezDph").prop("disabled");
		var valCenaSDphDisabled = $("#cenaSDph").prop("disabled");
		$.post("/save", {name : valName, cenaBezDph : valCenaBezDph, cenaSDph : valCenaSDph,
						 dph : valDph, cenaBezDphDisabled : valCenaBezDphDisabled,
						 cenaSDphDisabled : valCenaSDphDisabled, castkaDph : valCastkaDph}, function(data) {
		});
		$('#saveDialog').modal("hide");
	});

    $('#name').keypress(function (e) {
    	 var key = e.which;
    	 if(key == 13)  // the enter key code
    	  {
    	    $('.saveConfirm').click();
    	    return false;
    	  }
	});

    $.validator.messages.required = "Toto pole je povinné!";

    $("#submitForm").validate(
    		{
    			rules: {
    				name: {
    					required : true,
    					minlength : 1
    				}
    			},
    			highlight: function(element) {
    				$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    			},
    			unhighlight: function(element) {
    				$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
    			}
    		}
    );

});<|endoftext|>


<commit_before>"use strict"

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");
var DLModels = require("dl-models");
var map = DLModels.map;
var Storage = DLModels.master.Storage;
var BaseManager = require("module-toolkit").BaseManager;
var i18n = require("dl-i18n");

module.exports = class StorageManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.master.collection.Storage);
    }

    _getQuery(paging) {
        var _default = {
            _deleted: false
        },
            pagingFilter = paging.filter || {},
            keywordFilter = {},
            query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var codeFilter = {
                "code": {
                    "$regex": regex
                }
            };
            var nameFilter = {
                "name": {
                    "$regex": regex
                }
            };
            keywordFilter["$or"] = [codeFilter, nameFilter];
        }
        query["$and"] = [_default, keywordFilter, pagingFilter];
        return query;
    }

    _validate(storage) {
        var errors = {};
        var valid = storage;
        // 1. begin: Declare promises.
        var getBuyerPromise = this.collection.singleOrDefault({
            _id: {
                "$ne": new ObjectId(valid._id)
            },
            code: valid.code
        });
        // 2. begin: Validation.
        return Promise.all([getBuyerPromise])
            .then(results => {
                var _module = results[0];

                if (!valid.code || valid.code == "")
                    errors["code"] = i18n.__("Storage.code.isRequired:%s is required", i18n.__("Storage.code._:Code")); // "Kode harus diisi";
                else if (_module) {
                    errors["code"] = i18n.__("Storage.code.isExists:%s is already exists", i18n.__("Storage.code._:Code")); //"Kode sudah ada";
                }
                if (!valid.name || valid.name == '')
                    errors["name"] = i18n.__("Storage.name.isRequired:%s is required", i18n.__("Storage.name._:Name")); //"Nama Harus diisi";

                // 2c. begin: check if data has any error, reject if it has.
                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require("module-toolkit").ValidationError;
                    return Promise.reject(new ValidationError("data does not pass validation", errors));
                }
                if (!valid.tempo || valid.tempo == '')
                    valid.tempo = 0;

                valid = new Storage(valid);
                valid.stamp(this.user.username, "manager");
                return Promise.resolve(valid);
            });
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.master.collection.Storage}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        };

        var codeIndex = {
            name: `ix_${map.master.collection.Storage}_code`,
            key: {
                code: 1
            },
            unique: true
        };

        return this.collection.createIndexes([dateIndex, codeIndex]);
    }
}
<commit_msg>update storage manager<commit_after>"use strict"

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");
var DLModels = require("dl-models");
var map = DLModels.map;
var Storage = DLModels.master.Storage;
var BaseManager = require("module-toolkit").BaseManager;
var i18n = require("dl-i18n");
var CodeGenerator = require('../../utils/code-generator');

module.exports = class StorageManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.master.collection.Storage);
    }

    _getQuery(paging) {
        var _default = {
            _deleted: false
        },
            pagingFilter = paging.filter || {},
            keywordFilter = {},
            query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var codeFilter = {
                "code": {
                    "$regex": regex
                }
            };
            var nameFilter = {
                "name": {
                    "$regex": regex
                }
            };
            keywordFilter["$or"] = [codeFilter, nameFilter];
        }
        query["$and"] = [_default, keywordFilter, pagingFilter];
        return query;
    }

    _beforeInsert(storage) {
        storage.code = CodeGenerator();
        storage._active = true;
        return Promise.resolve(storage);
    }

    _validate(storage) {
        var errors = {};
        var valid = storage;
        // 1. begin: Declare promises.
        var getBuyerPromise = this.collection.singleOrDefault({
            _id: {
                "$ne": new ObjectId(valid._id)
            },
            code: valid.code
        });
        // 2. begin: Validation.
        return Promise.all([getBuyerPromise])
            .then(results => {
                var _module = results[0];

                if (_module) {
                    errors["code"] = i18n.__("Storage.code.isExists:%s is already exists", i18n.__("Storage.code._:Code")); //"Kode sudah ada";
                }
                if (!valid.name || valid.name == '')
                    errors["name"] = i18n.__("Storage.name.isRequired:%s is required", i18n.__("Storage.name._:Name")); //"Nama Harus diisi";

                // 2c. begin: check if data has any error, reject if it has.
                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require("module-toolkit").ValidationError;
                    return Promise.reject(new ValidationError("data does not pass validation", errors));
                }
                if (!valid.tempo || valid.tempo == '')
                    valid.tempo = 0;

                valid = new Storage(valid);
                valid.stamp(this.user.username, "manager");
                return Promise.resolve(valid);
            });
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.master.collection.Storage}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        };

        var codeIndex = {
            name: `ix_${map.master.collection.Storage}_code`,
            key: {
                code: 1
            },
            unique: true
        };

        return this.collection.createIndexes([dateIndex, codeIndex]);
    }
}
<|endoftext|>


<commit_before>import moment from 'moment';
import React from 'react';
import {ReverseLink} from 'react-router-reverse';
import urlJoin from 'url-join';

import * as constants from '../constants';

import {PageSection} from '../../site/components/page';

export class AddonListing extends React.Component {
  static propTypes = {
    addons: React.PropTypes.array.isRequired
  };

  render() {
    return (

        {this.props.addons.map(addon =>

            <Addon {...this.props} {...addon}/>

        )}
        {this.props.addons.length === 0 &&
No add-ons.
}

    );
  }
}

export class Addon extends React.Component {
  static propTypes = {
    description: React.PropTypes.string,
    isDisabled: React.PropTypes.bool.isRequired,
    latest_public_version: React.PropTypes.object,
    latest_version: React.PropTypes.object.isRequired,
    linkTo: React.PropTypes.string,
    mini_manifest_url: React.PropTypes.string.isRequired,
    showWaitingTime: React.PropTypes.bool,
    name: React.PropTypes.string.isRequired,
    slug: React.PropTypes.string.isRequired,
    status: React.PropTypes.string,
  };

  getMarketplaceUrl() {
    // FIXME: this is bad, mmkay?
    if (this.props.status === constants.STATUS_PUBLIC) {
      return urlJoin(process.env.MKT_ROOT, 'addon/', this.props.slug);
    }
  }

  renderWaitingTime() {
    if (this.props.latest_version &&
        this.props.latest_version.status == constants.STATUS_PENDING) {
      return (
        <di>

Time in Queue

            {moment().diff(this.props.latest_version.created, 'days')} Days

        </di>
      );
    }
  }

  renderName() {
    // If `linkTo`, have the header link to a more detailed page.
    if (this.props.linkTo) {
      return (
        <ReverseLink to={this.props.linkTo} params={{slug: this.props.slug}}>

{this.props.name}

        </ReverseLink>
      );
    }
    return
{this.props.name}

  }

  render() {
    const marketplaceURL = this.getMarketplaceUrl();
    return (

          {this.renderName()}

          <di>

Slug

{this.props.slug}

          </di>

          {this.props.showWaitingTime && this.renderWaitingTime()}

          <di>

Manifest

                Download manifest

          </di>

          {this.props.description &&
            <di>

Description

{this.props.description}

            </di>
          }

          {this.props.latest_public_version &&
            <di>

Latest Public Version

{this.props.latest_public_version.version}

Size

{this.props.latest_public_version.size}

            </di>
          }

          {this.props.latest_version &&
            <di>

Latest Submitted Version

{this.props.latest_version.version}

            </di>
          }

          {this.props.description &&
            <di>

Description

{this.props.description}

            </di>
          }

          {this.props.status &&
            <di>

Status

                {constants.humanizeAddonStatus(this.props.status,
                                               this.props.disabled)}

            </di>
          }

          {this.props.latest_version &&
            <di>

Last version uploaded

{this.props.latest_version.created}

            </di>
          }

          {marketplaceURL &&
            <di>

View on Marketplace

                {marketplaceURL}

            </di>
          }

    );
  }
}

export class AddonListingForDashboard extends AddonListing {
  render() {
    return (

        {this.props.addons.map(addon =>
          <AddonForDashboard {...this.props} {...addon}/>
        )}

    );
  }
}

export class AddonForDashboard extends Addon {
  renderLastUpdated() {
    if (this.props.latest_version) {
      return (
        <di>

Updated

            {moment(this.props.latest_version.created).format('MMMM Do, YYYY')}

        </di>
      );
    }
  }

  render() {
    const marketplaceURL = this.getMarketplaceUrl();
    return (

          <ReverseLink to={this.props.linkTo} params={{slug: this.props.slug}}>
            {this.props.name}
          </ReverseLink>

          <di className={`addon--status-${this.props.status}`}>

Status

              {constants.humanizeAddonStatus(this.props.status,
                                             this.props.disabled)}

          </di>
          {this.renderLastUpdated()}

              <ReverseLink to={this.props.linkTo}
                           params={{slug: this.props.slug}}>
                Edit this Add-on »
              </ReverseLink>

            {marketplaceURL &&

                  View on Marketplace »

            }

    );
  }
}

export class AddonForDashboardDetail extends Addon {
  renderAddonStatus() {
    return (

        {this.props.status === constants.STATUS_PUBLIC &&

            Your add-on
            is published.

        }
        {this.props.status === constants.STATUS_PENDING &&

              Your add-on is currently
              pending approval.

              You will receive an email when it has been reviewed.

        }
        {this.props.status === constants.STATUS_INCOMPLETE &&

              Your add-on has been
              rejected.

              You will receive an email with further instructions.

        }

    );
  }

  renderVersionStatuses() {
    return (

        {this.props.latest_version.status === constants.STATUS_PENDING &&

            Version {this.props.latest_version.version} of your add-on
            is pending approval.

        }
        {this.props.latest_version.status === constants.STATUS_REJECTED &&

            Version {this.props.latest_version.version} of your add-on
            has been rejected.

        }

          Version {this.props.latest_public_version.version} of your add-on
          is public.

    );
  }

  render() {
    return (
      <PageSection className="addon-dashboard-detail--status">
        {this.renderAddonStatus()}
        {this.props.status === constants.STATUS_PUBLIC &&
          this.renderVersionStatuses()
        }
      </PageSection>
    );
  }
}
<commit_msg>rm dupe desc<commit_after>import moment from 'moment';
import React from 'react';
import {ReverseLink} from 'react-router-reverse';
import urlJoin from 'url-join';

import * as constants from '../constants';

import {PageSection} from '../../site/components/page';

export class AddonListing extends React.Component {
  static propTypes = {
    addons: React.PropTypes.array.isRequired
  };

  render() {
    return (

        {this.props.addons.map(addon =>

            <Addon {...this.props} {...addon}/>

        )}
        {this.props.addons.length === 0 &&
No add-ons.
}

    );
  }
}

export class Addon extends React.Component {
  static propTypes = {
    description: React.PropTypes.string,
    isDisabled: React.PropTypes.bool.isRequired,
    latest_public_version: React.PropTypes.object,
    latest_version: React.PropTypes.object.isRequired,
    linkTo: React.PropTypes.string,
    mini_manifest_url: React.PropTypes.string.isRequired,
    showWaitingTime: React.PropTypes.bool,
    name: React.PropTypes.string.isRequired,
    slug: React.PropTypes.string.isRequired,
    status: React.PropTypes.string,
  };

  getMarketplaceUrl() {
    // FIXME: this is bad, mmkay?
    if (this.props.status === constants.STATUS_PUBLIC) {
      return urlJoin(process.env.MKT_ROOT, 'addon/', this.props.slug);
    }
  }

  renderWaitingTime() {
    if (this.props.latest_version &&
        this.props.latest_version.status == constants.STATUS_PENDING) {
      return (
        <di>

Time in Queue

            {moment().diff(this.props.latest_version.created, 'days')} Days

        </di>
      );
    }
  }

  renderName() {
    // If `linkTo`, have the header link to a more detailed page.
    if (this.props.linkTo) {
      return (
        <ReverseLink to={this.props.linkTo} params={{slug: this.props.slug}}>

{this.props.name}

        </ReverseLink>
      );
    }
    return
{this.props.name}

  }

  render() {
    const marketplaceURL = this.getMarketplaceUrl();
    return (

          {this.renderName()}

          <di>

Slug

{this.props.slug}

          </di>

          {this.props.showWaitingTime && this.renderWaitingTime()}

          <di>

Manifest

                Download manifest

          </di>

          {this.props.latest_public_version &&
            <di>

Latest Public Version

{this.props.latest_public_version.version}

Size

{this.props.latest_public_version.size}

            </di>
          }

          {this.props.latest_version &&
            <di>

Latest Submitted Version

{this.props.latest_version.version}

            </di>
          }

          {this.props.description &&
            <di>

Description

{this.props.description}

            </di>
          }

          {this.props.status &&
            <di>

Status

                {constants.humanizeAddonStatus(this.props.status,
                                               this.props.disabled)}

            </di>
          }

          {this.props.latest_version &&
            <di>

Last version uploaded

{this.props.latest_version.created}

            </di>
          }

          {marketplaceURL &&
            <di>

View on Marketplace

                {marketplaceURL}

            </di>
          }

    );
  }
}

export class AddonListingForDashboard extends AddonListing {
  render() {
    return (

        {this.props.addons.map(addon =>
          <AddonForDashboard {...this.props} {...addon}/>
        )}

    );
  }
}

export class AddonForDashboard extends Addon {
  renderLastUpdated() {
    if (this.props.latest_version) {
      return (
        <di>

Updated

            {moment(this.props.latest_version.created).format('MMMM Do, YYYY')}

        </di>
      );
    }
  }

  render() {
    const marketplaceURL = this.getMarketplaceUrl();
    return (

          <ReverseLink to={this.props.linkTo} params={{slug: this.props.slug}}>
            {this.props.name}
          </ReverseLink>

          <di className={`addon--status-${this.props.status}`}>

Status

              {constants.humanizeAddonStatus(this.props.status,
                                             this.props.disabled)}

          </di>
          {this.renderLastUpdated()}

              <ReverseLink to={this.props.linkTo}
                           params={{slug: this.props.slug}}>
                Edit this Add-on »
              </ReverseLink>

            {marketplaceURL &&

                  View on Marketplace »

            }

    );
  }
}

export class AddonForDashboardDetail extends Addon {
  renderAddonStatus() {
    return (

        {this.props.status === constants.STATUS_PUBLIC &&

            Your add-on
            is published.

        }
        {this.props.status === constants.STATUS_PENDING &&

              Your add-on is currently
              pending approval.

              You will receive an email when it has been reviewed.

        }
        {this.props.status === constants.STATUS_INCOMPLETE &&

              Your add-on has been
              rejected.

              You will receive an email with further instructions.

        }

    );
  }

  renderVersionStatuses() {
    return (

        {this.props.latest_version.status === constants.STATUS_PENDING &&

            Version {this.props.latest_version.version} of your add-on
            is pending approval.

        }
        {this.props.latest_version.status === constants.STATUS_REJECTED &&

            Version {this.props.latest_version.version} of your add-on
            has been rejected.

        }

          Version {this.props.latest_public_version.version} of your add-on
          is public.

    );
  }

  render() {
    return (
      <PageSection className="addon-dashboard-detail--status">
        {this.renderAddonStatus()}
        {this.props.status === constants.STATUS_PUBLIC &&
          this.renderVersionStatuses()
        }
      </PageSection>
    );
  }
}
<|endoftext|>


<commit_before>const http = require("../http.js");

function displayResultImage(cards) {
  return cards[0].image_uris.normal;
}

/**
 * @param {string} query
 * @param {function} cb
 */
function getCard(query, cb) {
  const URL = "https://api.scryfall.com/cards/search?" + query;
  http.get(URL, (err, body) => {
    if (err) {
      cb(err);
    } else {
      // console.log(JSON.stringify(body.data, null, 2));
      cb(null, body.data);
    }
  })
}

//todo encodeURIComponent
getCard("q=Negate", console.log);

function chatImageSearch(args, send, server, author, sendImg) {
  getCard("q=" + args.join(" "), (err, cards) => {
    if (err) {
      send(err)
    } else {
      sendImg("", displayResultImage(cards));
    }
  });
}

module.exports = {
  chatImageSearch
};<commit_msg>remove testing part<commit_after>const http = require("../http.js");

function displayResultImage(cards) {
  return cards[0].image_uris.normal;
}

/**
 * @param {string} query
 * @param {function} cb
 */
function getCard(query, cb) {
  const URL = "https://api.scryfall.com/cards/search?" + query;
  http.get(URL, (err, body) => {
    if (err) {
      cb(err);
    } else {
      // console.log(JSON.stringify(body.data, null, 2));
      cb(null, body.data);
    }
  })
}

//todo encodeURIComponent
// getCard("q=Negate", console.log);

function chatImageSearch(args, send, server, author, sendImg) {
  getCard("q=" + args.join(" "), (err, cards) => {
    if (err) {
      send(err)
    } else {
      sendImg("", displayResultImage(cards));
    }
  });
}

module.exports = {
  chatImageSearch
};<|endoftext|>