(function(){

    IApp_Portlet_Factory = {

        _instances : {},

        get : function (){
            var portlet = false;
            if( arguments.length > 0 ){

                if( portlet = IApp_Portlet_Factory.isRegistered( arguments[0] )){
                    if( arguments.length > 2 ){
                        portlet.setOptions( arguments[2] );
                       // portlet.init();
                    }

                    return portlet;
                }

                if( typeof arguments[0] == 'number' ){
                    if( ! portlet ){
                        portlet = IApp_Portlet_Factory.build.apply( IApp_Portlet_Factory, arguments );
                        if( arguments.length > 2 )
                            portlet.setOptions( arguments[2] );
                        portlet.init();
                    }else{
                        if( arguments.length > 2 )
                            portlet.setOptions( arguments[2] );
                    }

                    return portlet;
                }else if( typeof arguments[0] == 'string' ){
                    return IApp_Portlet_Factory.composite( arguments[0] );
                }
            }

            return false;
        },
        build : function( id, classname ){
            if( eval('typeof Portlet_' + classname) == 'function' ){
                portlet_class = 'Portlet_' + classname;
            }else{
                portlet_class = 'IApp_Portlet';
            }
            var portlet = eval('new ' + portlet_class + '(id, classname)');
            IApp_Portlet_Factory.register( id, portlet );

            if( composite = IApp_Portlet_Factory.isRegistered( classname ) ){
                composite.addInstance( portlet );
            }

            return portlet;
        },
        composite : function( key ){
            var composite = new IApp_Portlet_Composite();
            $.each( IApp_Portlet_Factory._instances, function(){
                if( this.classname == key )
                    composite.addInstance( this );
            });
            IApp_Portlet_Factory.register( key, composite );

            return composite;
        },
        register : function ( key, obj ){
            IApp_Portlet_Factory._instances[ key ] = obj;
        },
        isRegistered : function( key ){

            if( typeof key == 'object' )
                return key;

            if( typeof IApp_Portlet_Factory._instances[ key ] == 'object' )
                return IApp_Portlet_Factory._instances[ key ];

            return false;
        },
        setOptions : function( id, options ){
            IApp_Portlet_Factory.get( id ).setOptions( options );
        }
    };

})(jQuery);
