// vim: et:ts=4:sw=4:sts=4:ft=js

/*@
Ox.JQueryElement <function> Wrapper for jQuery
    # Usage
    ($element) -> <object> Wrapped jQuery DOM element
    # Arguments
    $element <object> jQuery DOM Element
@*/

Ox.JQueryElement = function($element) {
    var that = this;
    //@ id <number> Unique id
    that.id = Ox.uid();
    //@ ox <string> OxJS version
    that.ox = Ox.VERSION;
    //@ $element <object> The jQuery DOM element
    that.$element = $element.data({
        oxid: that.id
    });
    Ox.UI.elements[that.id] = that;
    return that;
};

// add all jQuery functions to the prototype of Ox.JQueryElement
Ox.forEach($('<div>'), function(val, key) {
    if (Ox.isFunction(val)) {
        Ox.JQueryElement.prototype[key] = function() {
            var args = arguments, id, ret, that = this;
            Ox.forEach(args, function(arg, i) {
                // if an ox object was passed
                // then pass its $element instead
                // so that we can do oxObj.jqFn(oxObj)
                if (arg && arg.ox) {
                    args[i] = arg.$element;
                }
            });
            ret = that.$element[key].apply(that.$element, args);
            // if the $element of an ox object was returned
            // then return the ox object instead
            // so that we can do oxObj.jqFn().oxFn()
            return ret && ret.jquery && Ox.UI.elements[id = ret.data('oxid')] ?
                    Ox.UI.elements[id] : ret;
        };
    }
});
