/**
 * Opensocial Framework
 * 
 * @author Melo <toosho@me.com>
 */
var osf = {
    /**
     * Error Title.
     */
    errors : {
        403 : '403 - Resource forbidden',
        404 : '404 - Page not Found',
        501 : '501 - Module not found ',
        503 : '503 - Service Unavailable'
    },

    /**
     * Initialyze framework.
     * @param appsite AppSite url.
     * @param appdata AppData url.
     */
    init : function (appsite, appdata) {
        osf.api.SITE = appsite;
        osf.api.CDN = appdata;

        var plugin;
        for (plugin in osf.jplugin) {
            jQuery.fn['Osf' + plugin] = osf.jplugin[plugin];
        }

        jQuery(document).ready(function () {
            osf.parser.html('body');

            //-- CheckBox Selection --//
            jQuery('.osfCheckBoxLabel').live('click', 'click', function (event) {
                var checkbox = jQuery(this).prev('.osfCheckBox');
                if (!checkbox.is(':disabled')) {
                    if (checkbox.is(':checked')) {
                        checkbox.attr('checked', false);
                        jQuery(this).removeClass('selected');
                    } else {
                        checkbox.attr('checked', true);
                        jQuery(this).addClass('selected');
                    }
                }
                return false;
            });

            //-- Radio Selection --//
            jQuery('.radio').change(function () {
                if (jQuery(this).is(':checked')) {
                    jQuery('.RadioSelected:not(:checked)').removeClass('RadioSelected');
                    jQuery(this).next('label').addClass('RadioSelected');
                }
            });

            //-- Ajax Error --//
            jQuery(document).ajaxError(function (event, xhr, settings, exception) {
                if (!osf.errors[xhr.status]) {
                    xhr.status = 404;
                    xhr.responseText = settings.url;
                }
                osf.window.alert({
                    id		: 'Error-' + xhr.status,
                    title	: 'Error ' + osf.errors[xhr.status],
                    width	: 600,
                    html	: xhr.responseText
                });
            });
        });
    },

    /**
     * Go to location.
     * @param url Url.
     */
    location : function (url) {
        document.location = url;
    },

    /**
     * Go to hash.
     * @param id Identifier.
     */
    hash : function (id) {
        document.location.hash = id;
    },

    /**
     * Validate input.
     * @param args Arguments.
     */
    validator : function (args) {
        var form = jQuery(args.id);
        if (0 < form.length) {
            if (args.errors.length == 0) {
                if (jQuery(args.id).data('validator')) {
                    jQuery(args.id).data('validator').reset();
                }
            } else {
                if (jQuery(args.id).data('validator')) {
                    jQuery(args.id).data('validator').invalidate(args.errors);
                }
            }
        }
    },

    /**
     * Toggle element.
     * @param id Identifier.
     */
    toggle : function (id) {
        jQuery(id).toggle();
    },

    /**
     * Show element.
     * @param id Identifier.
     */
    show : function (id) {
        jQuery(id).show();
    },

    /**
     * Hide element.
     * @param id Identifier.
     */
    hide : function (id) {
        jQuery(id).hide();
    },

    /**
     * Focus element.
     * @param id Identifier.
     */
    focus : function (id) {
        jQuery(id).focus();
    },

    /**
     * Remove element.
     * @param id Identifier.
     */
    remove : function (id) {
        jQuery(id).remove();
    },

    /**
     * Scroll to element.
     * @param id Identifier.
     */
    scrollTo : function (id) {
        jQuery.scrollTo(id);
    },

    /**
     * Append element.
     * @param args Arguments.
     */
    append: function (args) {
        jQuery(args.id).html(jQuery(args.id).html() + args.value);
        osf.parser.html(args.id);
    },

    /**
     * Add Css class to element.
     * @param args Arguments.
     */
    addClass : function (args) {
        jQuery(args.id).addClass(args.value);
    },

    /**
     * Remove Css class to element.
     * @param args Arguments.
     */
    removeClass : function (args) {
        jQuery(args.id).removeClass(args.value);
    },

    /**
     * Set attributes to element.
     * @param args Arguments.
     */
    set: function (args) {
        if (args.attr == 'html') {
            jQuery(args.id).html(args.value);
            osf.parser.html(args.id);
        } else if (args.attr == 'value') {
            jQuery(args.id).val(args.value);
        } else if (args.attr == 'ckeditor') {
            jQuery(args.id).ckeditor(function () {
                this.setData(args.value);
            });
        } else {
            jQuery(args.id).attr(args.attr, args.value);
        }
    },

    /**
     * Get attributes from element.
     * @param args Arguments.
     */
    get: function (args) {
        if (args.attr == 'html') {
            return jQuery(args.id).html();
        } else if (args.attr == 'ckeditor') {
            return jQuery(args.id).ckeditor(function () {
                this.getData();
            });
        } else {
            return jQuery(args.id).attr(args.attr);
        }
    },

    /**
     * Switch slideshow.
     */
    slideshow : function () {
        var active = jQuery('.slideshow A.active');
        if (active.length == 0) {
            active = jQuery('.slideshow A:last');
        }
        var next = active.next().length ? active.next() : jQuery('.slideshow A:first');
        var sibs = active.siblings();
        var rndNum = Math.floor(Math.random() * sibs.length);
        next = jQuery(sibs[rndNum]);
        active.addClass('last-active');
        next.css({
            opacity: 0.0
        }).addClass('active').animate({
            opacity: 1.0
        }, 1000, function () {
            active.removeClass('active last-active');
        });
    },

    /**
     * Check custombox.
     * @param args Arguments.
     */
    customBox : function (args) {
        var combo = jQuery('#' +  args.combo);
        if (0 < combo.length) {
            var selected = jQuery('#' + args.combo + ' option:selected');
            var item = jQuery('#' +  args.list);
            if (0 < item.length && 0 < selected.length && selected.attr('value') != '') {
                var limit = false;
                if (args.limit) {
                    limit = args.limit <= jQuery('.row', item).length;
                }
                if (!limit && 0 == jQuery("input[value='" + selected.attr('value') + "']", item).length) {
                    var li = document.createElement('DIV');
                    li.innerHTML = "<input type='hidden' name='" + args.name + "[]' value='" + selected.attr('value') + "'/><span class='btn24x24-texte p10l'>" + selected.attr('text') + "</span><a class='btn24x24 delete2 float-right' onclick='osf.remove(jQuery(this).parent())'>&nbsp;</a>";
                    li.className = 'row btn24x24-texte m5b p5t p5b';
                    item.append(li);
                    osf.parser.html(li.id);
                }
            }
            combo.attr('value', '');
        }
        jQuery('#' + args.combo).attr('value', null);
        return false;
    },

    /**
     * Sort UL list
     * @param ul List.
     * @param descending Sort descending.
     */
    sortList : function (ul, descending) {
        if (typeof ul == 'string') {
            ul = document.getElementById(ul);
        }
        if (!ul) {
            return;
        }

        //-- Get the list items and setup an array for sorting --//
        var lis = ul.getElementsByTagName('LI');
        var vals = [];
        var i = 0;
        var l = lis.length;

        //-- Populate the array --//
        for (i = 0, l = lis.length; i < l; i = i + 1) {
            vals.push(lis[i].innerHTML);
        }

        //-- Sort it --//
        vals.sort();

        //-- Descending --//
        if (descending) {
            vals.reverse();
        }

        //-- Change html value --//
        for (i = 0, l = lis.length; i < l; i = i + 1) {
            lis[i].innerHTML = vals[i];
        }
    },

    /**
     * AutoComplete.
     * @param url Url.
     * @param req Request.
     * @param add Element.
     */
    autocomplete : function (url, req, add) {
        jQuery.getJSON(url, req, function (data) {
            var suggestions = [];
            jQuery.each(data, function (i, val) {
                suggestions.push(val.name);
            });
            add(suggestions);
        });
    },

    /**
     * Ajax request.
     * @param opt Options.
     */
    ajax : function (opt) {
        var content = null;
        if (opt.content) {
            content = opt.content;
        }
        jQuery.ajax({
            type: 'POST',
            url: opt.url,
            data: content,
            dataType: 'json'
        }).success(function (data, status) {
            osf.parser.ajax(data);
        });
        return false;
    }
};

/**
 * Parser Manager
 */
osf.parser = {
    ajax: function (data) {
        var cpt;
        for (cpt = 0; cpt < data.length; cpt = cpt + 1) {
            try {
                var hitch = eval(data[cpt].fnc);
                hitch(data[cpt].args);
            } catch (err) {
                alert('Ajax Error : ' + data[cpt].fnc + ' is undefined' + err);
            }
        }
    },

    html : function (id) {
        jQuery(id == undefined ? '.osfWindow' : id + '.osfWindow, ' + id + ' .osfWindow').each(function () {
            jQuery(this).dialog(jQuery(this).metadata());
        });
        jQuery(id == undefined ? '.osfDialog' : id + '.osfDialog, ' + id + ' .osfDialog').each(function () {
            jQuery(this).dialog(jQuery(this).metadata());
        });
        jQuery(id == undefined ? '.osfFileInput' : id + '.osfFileInput, ' + id + ' .osfFileInput').filestyle();
        jQuery(id == undefined ? '.osfButton'	: id + '.osfButton, '	+ id + ' .osfButton').button();
        jQuery(id == undefined ? '.osfCombobox' : id + '.osfCombobox, ' + id + ' .osfCombobox').menu();
        jQuery(id == undefined ? '.osfTab' : id + '.osfTab, ' + id + ' .osfTab').tabs();
        jQuery(id == undefined ? '.osfAutoComplete' : id + '.osfAutoComplete, ' + id + ' .osfAutoComplete').each(function () {
            jQuery(this).autocomplete(jQuery(this).metadata());
        });
        jQuery(id == undefined ? '.osfDatePicker' : id + '.osfDatePicker, ' + id + ' .osfDatePicker').each(function () {
            jQuery(this).datepicker(jQuery(this).metadata());
        });
        jQuery(id == undefined ? '.osfTimePicker' : id + '.osfTimePicker, ' + id + ' .osfTimePicker').each(function () {
            jQuery(this).timepicker(jQuery(this).metadata());
        });
        jQuery(id == undefined ? '.osfFileUpload' : id + '.osfFileUpload, ' + id + ' .osfFileUpload').each(function () {
            jQuery(this).fileUpload(jQuery(this).metadata());
        });
        jQuery(id == undefined ? '.osfCheckBoxLabel' : id + '.osfCheckBoxLabel, ' + id + ' .osfCheckBoxLabel').each(function () {
            var checkbox = jQuery(this).prev('.osfCheckBox');
            if (checkbox.is(':checked')) {
                jQuery(this).addClass('selected');
            }
        });
        jQuery(id == undefined ? '.osfForm' : id + '.osfForm, ' + id + ' .osfForm').validator({
            message: '<div><em/></div>',
            errorClass: 'brderror bgerror'
        }).live('submit', 'submit', function (event) {
            if (!event.isDefaultPrevented()) {
                jQuery(this).ajaxSubmit({
                    type : 'post',
                    dataType : 'json',
                    data : {
                        timestamp: new Date().getTime()
                    },
                    success: function (data) {
                        osf.parser.ajax(data);
                    }
                });
                event.preventDefault();
            }
        });
        jQuery(id == undefined ? '.osfValidator' : id + '.osfValidator, ' + id + ' .osfValidator').validator({
            message: '<div><em/></div>',
            errorClass: 'brderror bgerror'
        });
        jQuery('input[placeholder], textarea[placeholder], .placeholder').each(function () {
            jQuery(this).placeholder();
        });
        jQuery('textarea.autogrow').each(function () {
            jQuery(this).autoResize({
                extraSpace: 0,
                animate: false
            });
        });
        jQuery(id == undefined ? '.osfPostWriter' : id + '.osfPostWriter, ' + id + ' .osfPostWriter').each(function () {
            jQuery(this).OsfPostWriter();
        });
        jQuery(id == undefined ? '.osfPostReader' : id + '.osfPostReader, ' + id + ' .osfPostReader').each(function () {
            jQuery(this).OsfPostReader();
        });
        jQuery(id == undefined ? '.osfCommentReader' : id + '.osfCommentReader, ' + id + ' .osfCommentReader').each(function () {
            jQuery(this).OsfCommentReader();
        });
        jQuery(id == undefined ? '.osfShare' : id + '.osfShare, ' + id + ' .osfShare').each(function () {
            jQuery(this).easyShare({
                title: 'Partager sur ...'
            });
        });
    }
};

/**
 * Windows Manager
 */
osf.window = {
    create: function (args) {
        if (0 < jQuery('#' + args.id).length) {
            jQuery('#' + args.id).html(args.html);
            osf.window.open(args.id);
            osf.parser.html('#' + args.id);
            osf.window.set({
                id : args.id,
                prop : 'position',
                value : 'center'
            });
        } else {
            var node = document.createElement('DIV');
            document.body.appendChild(node);
            node.id = args.id;
            node.title = (args.title != null ? args.title : 'OSF');
            node.className = 'osfWindow ' + args.params;
            node.innerHTML = (args.html != null ? args.html : '');
            osf.parser.html('#' + args.id);
            osf.window.open(args.id);
            osf.window.set({
                id : args.id,
                prop : 'position',
                value : 'center'
            });
        }
    },
    open: function (id) {
        jQuery('#' + id).dialog('open');
    },
    close: function (id) {
        jQuery('#' + id).dialog('close');
    },
    set: function (args) {
        var id = (args.id != null ? args.id : null);
        var prop = (args.prop != null ? args.prop : null);
        var value = (args.value != null ? args.value : null);
        if (id != null && prop != null && value != null) {
            jQuery('#' + id).dialog('option', prop, value);
        }
    },
    alert : function (args) {
        if (args.id == null) {
            var today = new Date();
            args.id = 'alert-' + today.getTime();
        }
        if (0 < jQuery('#' + args.id).length) {
            jQuery('#' + args.id).html(args.html);
            osf.window.open(args.id);
            osf.parser.html(args.id);
        } else {
            var node = document.createElement('DIV');
            document.body.appendChild(node);
            node.id = args.id;
            node.title = (args.title != null ? args.title : 'OSF');
            node.className = 'osfWindow {modal:true, resizable:false' + (args.width == null ? '' : ', width:' + args.width) + (args.height == null ? '' : ', height:' + args.height) + '}';
            node.innerHTML = (args.html != null ? args.html : '');
            osf.parser.html('#' + args.id);
            osf.window.open(args.id);
        }
    }
};

/**
 * Api.
 */
osf.api = {
    /**
     * Site url.
     */
    SITE : '',

    /**
     * CDN url.
     */
    CDN : ''
};

/**
 *  Link Manager.
 */
osf.api.link = {
    /**
     *  Check link .
     *  @param url link to check.
     *  @param userId Profile Identifier.
     */
    check : function (url, userId) {
        return osf.ajax({
            url: osf.api.SITE + 'post/checklink',
            content : {
                url : url,
                userId : userId
            }
        });
    },

    /**
     *  Analyze link.
     *  @param info link informations.
     */
    analyze : function (info) {
        if (info.userId) {
            jQuery('.osfPostWriter.user-' + info.userId).OsfPostWriter('linkAnalyze', info);
        }
    }
};

/**
 *  Post Manager.
 */
osf.api.post = {
    /**
     *  Check link .
     *  @param user User Id.
     *  @param after Post after Identifier.
     *  @param id Identifier.
     */
    refresh : function (user, after, id) {
        osf.ajax({
            url: osf.api.SITE + 'post/index/' + user + '/' + id,
            content : {
                after : after
            }
        });
    },

    /**
     *  Add Old Posts .
     *  @param arg Arguments.
     */
    before : function (arg) {
        jQuery('.osfPostReader.user-' + arg.userId).OsfPostReader('before', arg);
    },

    /**
     *  Add New Posts .
     *  @param arg Arguments.
     */
    after : function (arg) {
        jQuery('.osfPostReader.user-' + arg.userId).OsfPostReader('after', arg);
    },

    /**
     *  Pusblish new post.
     *  @param arg Arguments {user,text,attachments}
     */
    publish : function (arg) {
        osf.ajax({
            url: osf.api.SITE + 'post/add/' + arg.user,
            content : {
                content : arg.text,
                attachments : arg.attachments
            }
        });
    },

    update : function (arg) {
        jQuery('.osfPostWriter.user-' + arg.userId).OsfPostWriter('update', arg);
    }
};

/**
 *  Comment Manager.
 */
osf.api.comment = {
    /**
     *  Check link .
     *  @param obj Object Identifier.
     *  @param after Comment after Identifier.
     *  @param id Identifier.
     */
    refresh : function (obj, after, id) {
        osf.ajax({
            url: osf.api.SITE + 'comment/index/' + obj + '/' + id,
            content : {
                after : after
            }
        });
    },

    /**
     *  Add Old Comment .
     *  @param arg Arguments.
     */
    before : function (arg) {
        jQuery('.osfCommentReader.obj-' + arg.objId).OsfCommentReader('before', arg);
    },

    /**
     *  Add New Comment .
     *  @param arg Arguments.
     */
    after : function (arg) {
        jQuery('.osfCommentReader.obj-' + arg.objId).OsfCommentReader('after', arg);
    },

    /**
     *  Pusblish New Comment.
     *  @param arg Arguments {user,text,attachments}
     */
    publish : function (arg) {
        osf.ajax({
            url: osf.api.SITE + 'comment/add/' + arg.objId + '/' + arg.newId,
            content : {
                content : arg.text,
                after : true
            }
        });
    }
};

osf.api.object = {
    like : function (arg) {
    
    },
    
    unlike : function (arg) {
    
    },
    
    share : function (arg) {
        if(arg.action){
            switch(arg.action){
                case 'init' : 
                    osf.ajax({
                        url: osf.api.SITE + 'post/share',
                        content : {
                            id : arg.objId
                        }
                    });
                    break;
                case 'publish' : 
                    osf.ajax({
                        url: osf.api.SITE + 'post/share',
                        content : {
                            confirm : true,
                            id : arg.objId
                        }
                    });
                    break;
                case 'show' :
                    jQuery('.osfShare.obj-' + arg.objId).OsfShare('show', arg);
                    break;
                case 'close' : 
                    jQuery('.osfShare.obj-' + arg.objId).OsfShare('close', arg);
                    break;
            }
        }
    }
}

/**
 * OSF JQUERY PLUGINS
 */
jQuery.OsfPostReader = {
    minHeight : 55,
    txt : {
        loadingData : 'Loading data...',
        shareTitle : 'Share on...',
        shareBookmark : 'Press"Ctrl+D" or "Cmd+D" on Mac in order to add to bookmark.'
    }
};
jQuery.OsfPostWriter = {
    limitContent : 250,
    txt : {
        placeHolderContent : 'Express yourself',
        analysisInProgress : 'Analysis in progress',
        links : 'Links',
        gallery : 'Images / Videos',
        publish : 'Publish',
        attachment : 'Attachment'
    }
};
jQuery.OsfCommentReader = {
    txt : {
        publish : 'Post',
        loadingData : 'Loading comments...'
    }
};

osf.jplugin = {
    /**
     *  jQuery.OsfPostComment Plugin.
     *  @version 1.0
     *  @autheur Melo <toosho@me.com>
     */
    Share : function (method) {
        this['class'] = {
            /**
             *  Initialyze Share Manager.
             */
            init : function () {
                var plugin = this['class'];
                return this.each(function () {
                    var elt = jQuery(this);
                    var data = elt.data('osfshare');
                    if (!data) {
                        if (elt.metadata() && elt.metadata().id) {
                            elt.data('osfshare', {
                                objId : elt.metadata().id,
                                tmpId : 0,
                                oldId : 0,
                                newId : 0
                            });
                        }
                    }
                });
            },
            
            /**
             * Prepare Share Window.
             */
            prepare : function () {
                var elt = this;
                var data = elt.data('osfshare');
                if (data) {
                    osf.api.object.share({action:'init', objId : data.objId});
                }
            },
            

            /**
             *  Show Share Window.
             *  
             *  @param Object args Arguments
             */
            show : function (args) {
                var elt = this;
                var data = elt.data('osfshare');
                if (data) {
                    osf.window.create({
                        id : 'dlgObjectShare',
                        title : args.title,
                        params : 'p10  {autoOpen: false, modal: true, width:500,resizable:false}',
                        html : args.value
                    });
                }
            },
            
            /**
             *  Close Share Window.
             *  
             *  @param Object args Arguments
             */
            close : function (args) {
                var elt = this;
                var data = elt.data('osfshare');
                if (data) {
                    if(args.error){
                        
                    } else {
                        osf.set({
                        'id' : '.links-' + data.objId + ' .share .number',
                        'attr' : 'html',
                        'value' : args.number
                        });
                        osf.set({
                        'id' : '#dlgObjectShare',
                        'attr' : 'html',
                        'value' : args.msg
                        });
                        osf.window.set({
                            id : 'dlgObjectShare',
                            prop : 'position',
                            value : 'center'
                        });
                        //osf.window.close('dlgObjectShare');
                    }
                }
            },

            /**
             *  Add Comment Manager
             */
            publish : function () {
                var data = this.data('osfshare');
                if (data) {
                    osf.api.object.share({action:'publish', objId : data.objId});
                }
            }
        };
        if (this['class'][method]) {
            return this['class'][method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return this['class'].init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist ');
            return null;
        }
    },

    /**
     *  jQuery.OsfPostComment Plugin.
     *  @version 1.0
     *  @autheur Melo <toosho@me.com>
     */
    CommentReader : function (method) {
        this['class'] = {
            /**
             *  Initialyze reader.
             */
            init : function () {
                var plugin = this['class'];
                return this.each(function () {
                    var elt = $(this);
                    var data = elt.data('commentreader');
                    if (!data) {
                        if (elt.metadata() && elt.metadata().id) {
                            elt.data('commentreader', {
                                initialized : false,
                                objId : elt.metadata().id,
                                tmpId : 0,
                                oldId : 0,
                                newId : 0
                            });
                            var add = jQuery('<div/>').addClass('comment add').css('display', 'none').append(
                                jQuery('<span>&nbsp;</span>').addClass('avatar')
                                ).append(
                                jQuery('<div/>').addClass('message').append(
                                    jQuery('<p>').append(
                                        jQuery('<textarea/>').addClass('brd2 nofocus autogrow')
                                        )
                                    ).append(
                                    jQuery('<a>').addClass('publish cursor pointer').html(jQuery.OsfCommentReader.txt.publish).click(function () {
                                        var textarea = add.find('textarea');
                                        if (textarea.val() != '') {
                                            osf.api.comment.publish({
                                                objId : elt.metadata().id,
                                                text : textarea.val(),
                                                newId : elt.data('commentreader').newId
                                            });
                                            textarea.val("");
                                            textarea.height('26');
                                        }
                                    })
                                    )
                                );
                            elt.append(add);
                        }
                    }
                });
            },

            /**
             *  Toggle Comment Manager
             */
            toggle : function () {
                var data = this.data('commentreader');
                if (data) {
                    if (!data.initialized) {
                        data.initialized = true;
                        this.data('commentreader', data);
                        this.append(jQuery('<div/>').addClass('comment old').append(jQuery('<span>&nbsp;</span>').addClass('icon-24x24 loader')).append(jQuery('<span/>').addClass('icon-24x24 texte m10l').html(jQuery.OsfCommentReader.txt.loadingData)));
                        osf.api.comment.refresh(data.objId, true, data.newId);
                    }
                    jQuery(this).toggle();
                    jQuery('.osfPostReader').OsfPostReader('resize');
                }
            },

            /**
             *  Add Comment Manager
             */
            add : function () {
                var data = this.data('commentreader');
                if (data) {
                    if (!data.initialized) {
                        data.initialized = true;
                        this.data('commentreader', data);
                        this.append(jQuery('<div/>').addClass('comment old').append(jQuery('<span>&nbsp;</span>').addClass('icon-24x24 loader')).append(jQuery('<span/>').addClass('icon-24x24 texte m10l').html(jQuery.OsfCommentReader.txt.loadingData)));
                        osf.api.comment.refresh(data.objId, true, data.newId);
                    }
                    jQuery(this).toggle();
                }
            },

            /**
             *  Get New Posts  after newId.
             */
            refresh : function () {
                var data = this.data('commentreader');
                if (data) {
                    osf.api.comment.refresh(data.objId, true, data.newId);
                }
            },

            /**
             *  Get old Posts before oldId.
             */
            old : function () {
                var data = this.data('commentreader');
                if (data) {
                    osf.api.comment.refresh(data.objId, false, data.oldId);
                }
            },

            /**
             *  Add Old Posts
             *  @param arg Arguments.
             */
            before : function (arg) {
                var data = this.data('commentreader');
                if (data) {
                    if (0 < arg.id) {
                        data.oldId = arg.id;
                        this.data('commentreader', data);
                    }
                    this.find('.comment.old').remove();
                    if (arg.value) {
                        this.append(jQuery(arg.value));
                        osf.parser.html('.osfCommentReader.obj-' + arg.objId + ' #comment-' + arg.id);
                    }
                    if (arg.total) {
                        jQuery('.links-' + arg.objId + ' .comment .number').html(arg.total);
                    }
                    jQuery('.osfPostReader').OsfPostReader('resize');
                }
            },

            /**
             *  Add New Posts .
             *  @param arg Arguments.
             */
            after : function (arg) {
                var data = this.data('commentreader');
                if (data) {
                    if (0 < arg.id) {
                        data.newId = arg.id;
                        this.data('commentreader', data);
                    }
                    if (arg.value) {
                        this.find('.comment.add').after(jQuery(arg.value));
                    }
                    if (arg.total) {
                        jQuery('.links-' + arg.objId + ' .comment .number').html(arg.total);
                    }
                    jQuery('.osfPostReader').OsfPostReader('resize');
                }
            }
        };
        if (this['class'][method]) {
            return this['class'][method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return this['class'].init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist ');
            return null;
        }
    },

    /**
     *  jQuery.OsfPostReader Plugin.
     *  @version 1.0
     *  @autheur Melo <toosho@me.com>
     */
    PostReader : function (method) {
        this['class'] = {
            /**
             *  Initialyze reader.
             */
            init : function () {
                var plugin = this['class'];
                return this.each(function () {
                    var elt = $(this);
                    var data = elt.data('postreader');
                    if (!data) {
                        if (elt.metadata() && elt.metadata().id) {
                            elt.data('postreader', {
                                userId : elt.metadata().id,
                                tmpId : 0,
                                oldId : 0,
                                newId : 0
                            });
                            elt.parent().addClass('osfPostReaderParent user-' + elt.metadata().id);
                            var slider = jQuery('<div/>').addClass('slider');
                            var loader = jQuery('<p/>').addClass('align-center post-old').append(jQuery('<span>&nbsp;</span>').addClass('icon-24x24 loader')).append(jQuery('<span/>').addClass('icon-24x24 texte m10l').html(jQuery.OsfPostReader.txt.loadingData));
                            var content = jQuery('<div/>').addClass('content').html(loader);
                            elt.addClass('nofocus jScrollbar').append(content).append(slider);
                            jQuery(document).ready(function () {
                                slider.height(elt.height() - parseInt(slider.css('top'), 10));
                                slider.slider({
                                    orientation: 'vertical',
                                    min : 0,
                                    max : 10000,
                                    value : 10000,
                                    slide : function (e, ui) {
                                        var height = content.height() - elt.height();
                                        if (0 < height) {
                                            content.css('top', '-' + (height - ui.value * height / 10000) + 'px');
                                        }
                                    },
                                    change : function (e, ui) {
                                        var data = elt.data('postreader');
                                        if (ui.value <= 24 && data.tmpId != data.oldId) {
                                            var old = elt.find('.post-old');
                                            if (0 < old.length) {
                                                elt.OsfPostReader("old");
                                            }
                                            data.tmpId = data.oldId;
                                            elt.data('postreader', data);
                                        }
                                    }
                                });
                                elt.mousewheel(function (objEvent, intDelta) {
                                    var pxval = parseInt(content.css('top'), 10);
                                    pxval = parseInt(pxval + 20 * intDelta, 10);
                                    var height = -(content.height() - elt.height());
                                    if (pxval <= height) {
                                        pxval = height;
                                    }
                                    if (0 < pxval) {
                                        pxval = 0;
                                    }
                                    content.css('top', pxval + 'px');
                                    slider.slider('value', (Math.abs(pxval) + height) /  (height / 10000));
                                });
                                elt.OsfPostReader('resize');
                                elt.OsfPostReader('refresh');
                            });
                            jQuery(window).bind("resize", function () {
                                elt.OsfPostReader('resize');
                            });
                        }
                    }
                });
            },

            /**
             *  Resize Reader.
             */
            resize : function () {
                var data = this.data('postreader');
                if (data) {
                    var content = this.find('.content');
                    var slider = this.find('.slider');
                    slider.height(this.height() - parseInt(slider.css('top'), 10));

                    var pxval = parseInt(content.css('top'), 10);
                    var height = -(content.height() - this.height());
                    if (pxval <= height) {
                        pxval = height;
                    }
                    if (0 < pxval) {
                        pxval = 0;
                    }
                    content.css('top', pxval + 'px');
                    slider.slider('value', (Math.abs(pxval) + height) /  (height / 10000));
                    if (this.height() <= content.height()) {
                        slider.find('.ui-slider-handle').css('display', 'block');
                    } else {
                        slider.find('.ui-slider-handle').css('display', 'none');
                    }
                }
            },

            /**
             *  Get New Posts  after newId.
             */
            refresh : function () {
                var data = this.data('postreader');
                if (data) {
                    osf.api.post.refresh(data.userId, true, data.newId);
                }
            },

            /**
             *  Get old Posts before oldId.
             */
            old : function () {
                var data = this.data('postreader');
                if (data) {
                    osf.api.post.refresh(data.userId, false, data.oldId);
                }
            },

            /**
             *  Add Old Posts
             *  @param arg Arguments.
             */
            before : function (arg) {
                var data = this.data('postreader');
                if (data) {
                    if (0 < arg.id) {
                        data.oldId = arg.id;
                        this.data('postreader', data);
                    }
                    this.find('.post-old').remove();
                    if (arg.value) {
                        var content = this.find('.content');
                        var o = content.height();
                        var post = jQuery(arg.value);
                        content.append(post);
                        post.find('.osfCommentReader').each(function () {
                            jQuery(this).OsfCommentReader();
                        });
                        post.find('.osfShare').each(function () {
                            jQuery(this).OsfShare();
                        });
                        osf.parser.html('.osfPostReaderParent user-' + arg.userId + ' .content');
                    }
                    this.OsfPostReader('resize');
                }
            },

            /**
             *  Add New Posts .
             *  @param arg Arguments.
             */
            after : function (arg) {
                var data = this.data('postreader');
                if (data) {
                    if (0 < arg.id) {
                        data.newId = arg.id;
                        this.data('postreader', data);
                    }
                    this.find('.post-old').remove();
                    if (arg.value) {
                        var content = this.find('.content');
                        var o = content.height();
                        var post = jQuery(arg.value);
                        content.prepend(post);
                        post.find('.osfCommentReader').each(function () {
                            jQuery(this).OsfCommentReader();
                        });
                        post.find('.osfShare').each(function () {
                            jQuery(this).OsfShare();
                        });
                        osf.parser.html('.osfPostReaderParent user-' + arg.userId + ' .content');
                    }
                    this.OsfPostReader('resize');
                }
            }
        };
        if (this['class'][method]) {
            return this['class'][method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return this['class'].init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist ');
            return null;
        }
    },

    /**
     *  jQuery.OsfPostWriter Plugin
     *  @version 1.0
     *  @autheur Melo <toosho@me.com>
     */
    PostWriter : function (method) {
        this['class'] = {
            /**
             *  Initialyze writer.
             */
            init : function () {
                var plugin = this['class'];
                return this.each(function () {
                    var elt = $(this);
                    var data = elt.data('postwriter');
                    if (!data) {
                        if (elt.metadata() && elt.metadata().id) {
                            elt.data('postwriter', {
                                userId : elt.metadata().id,
                                galleryWidth : 0
                            });
                            elt.parent().addClass('osfPostWriterParent user-'+elt.metadata().id);
                            elt.append(
                                $('<div/>').
                                addClass('p10t brd2b p10b').
                                append(
                                    $('<div/>').
                                    addClass('relative p10l p20r').
                                    append(
                                        $('<textarea/>').
                                        addClass('relative content p10l p10l p10r nofocus brd2').
                                        attr({
                                            name : 'content', 
                                            'placeholder' : jQuery.OsfPostWriter.txt.placeHolderContent
                                        }).
                                        css({
                                            width:'100%', 
                                            padding : '0px 5px'
                                        }).
                                        focusin(function() {
                                            elt.OsfPostWriter('expand');
                                        }).focusout(function() {
                                            elt.OsfPostWriter('reduce');
                                        }).keyup(function() {
                                            elt.OsfPostWriter('limit');
                                        }).keydown(function() {
                                            elt.OsfPostWriter('limit');
                                        }).placeholder()
                                        ).
                                    append(
                                        $('<div/>').
                                        addClass('absolute analyse p5 brd2t brd2l bgwhite').
                                        css({
                                            display:'none', 
                                            bottom : '0px', 
                                            right : '10px'
                                        }).
                                        html(jQuery.OsfPostWriter.txt.analysisInProgress)
                                        )
                                    ).
                                append(
                                    $('<div/>').
                                    addClass('p10l').
                                    css({
                                        'padding-right' : '8px'
                                    }).
                                    append(
                                        $('<section/>').
                                        addClass('gallery brd2l brd2r').
                                        append(
                                            $('<header/>').
                                            addClass('skip').
                                            append($('<h5/>').html(jQuery.OsfPostWriter.txt.gallery))
                                            ).
                                        append(
                                            $('<div/>').
                                            addClass('table').
                                            css({
                                                'display' : 'none'
                                            }).
                                            append(
                                                $('<div/>').
                                                addClass('tr').
                                                append(
                                                    $('<div>&lt;</div>').
                                                    addClass('td brd2r align-center cursor pointer').
                                                    css({
                                                        width : '24px', 
                                                        height : '125px', 
                                                        'line-height' : '125px'
                                                    }).
                                                    click(function () {
                                                        elt.OsfPostWriter('mediaPrevious');
                                                    })
                                                    ).
                                                append(
                                                    $('<div/>').
                                                    addClass('p5 relative').
                                                    css({
                                                        'white-space' : 'nowrap', 
                                                        'overflow' : 'hidden', 
                                                        height : '100%'
                                                    }).
                                                    append($('<div/>').addClass('content absolute'))
                                                    ).
                                                append(
                                                    $('<div>&gt;</div>').
                                                    addClass('td brd2l align-center cursor pointer').
                                                    css({
                                                        width : '24px', 
                                                        height : '125px', 
                                                        'line-height' : '125px'
                                                    }).
                                                    click(function () {
                                                        elt.OsfPostWriter('mediaNext');
                                                    })
                                                    )
                                                )
                                            )
                                        ).
                                    append(
                                        $('<section/>').addClass('links brd2l brd2r').
                                        append($('<header/>').addClass('skip').append($('<h5/>').html(jQuery.OsfPostWriter.txt.links)))
                                        )
                                    ).
                                append(
                                    $('<div/>').addClass('p10l p20r').
                                    append(
                                        $('<section/>').addClass('add brd2l brd2r brd2b p5l p5r').css({
                                            width : '100%'
                                        }).
                                        append($('<header/>').addClass('skip').append($('<h4/>').html(jQuery.OsfPostWriter.txt.attachment))).
                                        append(
                                            $('<div/>').addClass('table').
                                            append(
                                                $('<div/>').addClass('tr').
                                                append(
                                                    $('<div/>').addClass('td').css({
                                                        width : '16px', 
                                                        height : '24px', 
                                                        'line-height' : '24px'
                                                    }).
                                                    append($('<span>&nbsp;</span>').addClass('icon-16x16 link over').css({
                                                        'vertical-align' : 'middle'
                                                    }))
                                                    ).
                                                append(
                                                    $('<div/>').addClass('td').css({
                                                        height : '24px', 
                                                        'line-height' : '24px'
                                                    }).
                                                    append($('<input/>').addClass('brdnone nofocus').attr({
                                                        placeholder : 'http//'
                                                    }).css({
                                                        width : '100%', 
                                                        height : '24px', 
                                                        'line-height' : '24px', 
                                                        'vertical-align' : 'middle'
                                                    }).keypress(function (e) {
                                                        var code = (e.keyCode ? e.keyCode : e.which);
                                                        if (code == 13) {
                                                            elt.OsfPostWriter('linkCheck',$(this).val());
                                                            $(this).val('');
                                                            return false;
                                                        } else {
                                                            return true;
                                                        }
                                                    }))
                                                    ).
                                                append(
                                                    $('<div/>').addClass('td').css({
                                                        width : '30px', 
                                                        height : '24px', 
                                                        'line-height' : '24px', 
                                                        'text-align' : 'center'
                                                    }).
                                                    append($('<a>').append($('<span/>').addClass('icon-16x16 texte brd2 align-center').css({
                                                        'vertical-align' : 'middle', 
                                                        'width' : '18px'
                                                    }).html('+').click(function () {
                                                        var input = elt.find('input');
                                                        elt.OsfPostWriter('linkCheck',input.val());
                                                        input.val('');
                                                        osf.api.link.check(jQuery("#'.$this->activity->formName().' .add input"))
                                                    })))
                                                    ).
                                                append(
                                                    $('<div/>').addClass('td p5l brd2l').css({
                                                        width : '70px', 
                                                        height : '24px', 
                                                        'line-height' : '24px', 
                                                        'text-align' : 'center'
                                                    }).
                                                    append($('<a>').append($('<span>&nbsp;</span>').addClass('icon-16x16 photo').css({
                                                        'vertical-align' : 'middle'
                                                    }))).
                                                    append($('<a>').addClass('m10l').append($('<span>&nbsp;</span>').addClass('icon-16x16 video').css({
                                                        'vertical-align' : 'middle'
                                                    }))).
                                                    append($('<a>').addClass('m5l').append($('<span>&nbsp;</span>').addClass('icon-16x16 localisation').css({
                                                        'vertical-align' : 'middle'
                                                    })))
                                                    )
                                                )
                                            )
                                        )
                                    ).
                                append(
                                    $('<p/>').addClass('p10l p10r p5t').css({
                                        'display' : 'none'
                                    }).
                                    append($('<button/>').addClass('content-publish osfButton').attr({
                                        type : 'button'
                                    }).html(jQuery.OsfPostWriter.txt.publish).click(function(){
                                        elt.OsfPostWriter('publish');
                                    }).button().attr('disabled',true)).
                                    append($('<span/>').addClass('content-length bold m5l').css({
                                        'font-size' : '1.3em', 
                                        height : '28px', 
                                        'line-height' : '28px'
                                    }).html(jQuery.OsfPostWriter.limitContent))
                                    )
                                );
                            
                            $(document).ready(function () {
                                elt.data('postwriter', {
                                    userId : elt.metadata().id,
                                    galleryWidth : elt.find('.gallery').width() - 50
                                });
                                elt.find('.gallery .content').parent().css({
                                    "max-width":elt.find('.gallery .content').css("width")-48
                                }).show();  
                            });
                            
                            $(window).bind("resize", function(){
                                elt.data('postwriter', {
                                    userId : elt.metadata().id,
                                    galleryWidth : elt.find('.gallery').width() - 50
                                });
                                elt.find('.gallery .content').parent().css({
                                    "max-width":elt.find('.gallery .content').css("width")-48
                                }).show();  
                            });
                        }
                    }
                });
            },
            expand : function () {
                var data = this.data('postwriter');
                if (data) {
                    this.find('.content').css({
                        height : 68, 
                        'max-height' : '68px', 
                        'min-height': '68px'
                    });
                    this.find('.content-length').parent().show();
                    $('.osfPostReader.user-' + data.userId).OsfPostReader('resize');
                }
            },
            reduce : function () {
                var data = this.data('postwriter');
                if (data) {
                    var value = this.find('.content');
                    if(value.val() == ''){
                        value.css({
                            height : 24, 
                            'max-height' : '24px', 
                            'min-height' : '24px'
                        });
                        var attachments = [];
                        this.find('.attachment').each(function(){
                            attachments.push(jQuery(this).val());
                        });
                        if(0 == attachments.length){
                            this.find('.content-length').parent().hide();
                        }
                        $('.osfPostReader.user-' + data.userId).OsfPostReader('resize');
                    }
                }
            },
            publish : function(){
                var data = this.data('postwriter');
                if (data) {
                    var text = this.find('.content');
                    var attachments = [];
                    this.find('.attachment').each(function(){
                        attachments.push(jQuery(this).val());
                    });
                    if(text.val() != '' || 0 < attachments.length){
                        osf.api.post.publish({
                            user:data.userId, 
                            text:text.val(), 
                            attachments:attachments
                        });
                    }
                }
            },
            update : function(){
                var data = this.data('postwriter');
                if (data) {
                    this.data('postwriter',null);
                    this.find('.content').val('');
                    this.html('');
                    this.OsfPostWriter();
                    $('.osfPostReader.user-' + data.userId).OsfPostReader('refresh');
                    $('.osfPostReader.user-' + data.userId).OsfPostReader('resize');
                }
            },
            limit : function () {
                var data = this.data('postwriter');
                if (data) {
                    var value = this.find('.content').val();
                    var length = this.find('.content-length');
                    if(0 < value.length){
                        this.find('.content-publish').attr("disabled", false);
                    } else {
                        this.find('.content-publish').attr("disabled", true);
                    }
                        
                    if (value.length > jQuery.OsfPostWriter.limitContent){
                        length.addClass("color1");
                    } else {
                        length.removeClass("color1");
                    }
                    length.html(jQuery.OsfPostWriter.limitContent - value.length);
                }
            },
            mediaPrevious : function(){
                var data = this.data('postwriter');
                if (data) {
                    var opos = this.find('.gallery .content').position();
                    var mpos = this.find('.gallery .content').parent().width();
                    var pos = 5;
                    opos = opos.left;
                    this.find('.gallery article.photo').each(function(index){
                        var item = jQuery(this);
                        var p = item.position();
                        var w = item.width();
                        p = p.left;
                        if(opos + p < 0){
                            pos = -p + 5;
                        }
                    });
                    if(pos <= 5){
                        this.find('.gallery .content').animate({
                            left:pos+"px"
                        });
                    }
                }
            },
            mediaNext : function(){
                var data = this.data('postwriter');
                if (data) {
                    var opos = this.find('.gallery .content').position();
                    var mpos = this.find('.gallery .content').parent().width();
                    var pos = 5;
                    opos = opos.left;
                    this.find('.gallery article.photo').each(function(index){
                        var item = jQuery(this);
                        var p = item.position();
                        var w = item.width();
                        p = p.left;
                        if(opos + p - w < mpos){
                            pos = p + w - mpos - 5;
                        }
                    });
                    if(5 < pos){
                        this.find('.gallery .content').animate({
                            left:"-"+pos+"px"
                        });
                    }
                }
            
            },
            mediaDelete : function(item) {
                var data = this.data('postwriter');
                if (data) {
                    var me = this;
                    jQuery(item).parent().fadeOut(function(){
                        jQuery(this).remove();
                        if(me.find('.gallery article.photo, .gallery article.video').length == 0){
                            me.find('.gallery .table').hide();  
                            me.find('.gallery').removeClass("brd2b");  
                        }
                        var text = me.find('.content');
                        var attachments = [];
                        me.find('.attachment').each(function(){
                            attachments.push(jQuery(this).val());
                        });
                        if(text.val() == '' && 0 == attachments.length){
                            me.find('.content-length').parent().hide();
                            me.find('.content-publish').attr("disabled", true);
                        }
                        $('.osfPostReader.user-' + data.userId).OsfPostReader('resize');
                    });
                }
            },
            mediaView : function (item) {
                var overlay = jQuery("<section/>").
                css({
                    width:"100%", 
                    height:"100%", 
                    "background-color": "#000", 
                    position: "fixed", 
                    top: "0px", 
                    left: "0px"
                }).
                append(
                    jQuery("<div>").
                    addClass("table").
                    append(
                        jQuery("<div>").
                        addClass("tr").
                        css({
                            "height":"40px"
                        }).
                        append(
                            jQuery("<div>").
                            addClass("td").
                            css({
                                "width":"40px",
                                "height":"40px"
                            })
                            ).
                        append(
                            jQuery("<div>").
                            addClass("td").
                            append(
                                jQuery("<header/>").
                                append(
                                    jQuery("<h1/>").
                                    html("Pas de titre")
                                    ).
                                css({
                                    margin:"0px", 
                                    padding:"0px", 
                                    height:"40px",
                                    "line-height":"40px"
                                })
                                )
                            ).
                        append(
                            jQuery("<div>").
                            addClass("td").
                            css({
                                "width":"300px",
                                "height":"40px"
                            })
                            ).
                        append(
                            jQuery("<div>").
                            addClass("td align-center").
                            css({
                                "width":"40px",
                                "height":"40px",
                                "line-height":"40px"
                            }).
                            append(
                                jQuery("<span/>").
                                html("&nbsp;").
                                addClass("icon-24x24 delete3").
                                css({
                                    "background-color":"#222222",
                                    "border":"1px solid #000",
                                    "border-radius":"3px",
                                    "vertical-align":"middle"
                                }).
                                click(function(){
                                    jQuery(this).parent().parent().parent().parent().remove();
                                })
                                )
                            )
                        ).
                    append(
                        jQuery("<div>").
                        addClass("tr").
                        append(
                            jQuery("<div>&lt;</div>").
                            addClass("td align-center").
                            css({
                                "width":"40px",
                                height:(jQuery(window).height()-110)+"px",
                                "line-height":(jQuery(window).height()-110)+"px"
                            })
                            ).
                        append(
                            jQuery("<div>").
                            addClass("td align-center").
                            append(
                                jQuery("<div/>").
                                append(
                                    jQuery("<img/>").
                                    attr({
                                        src:item.url
                                    }).
                                    css({
                                        "max-height":(jQuery(window).height()-110)+"px"
                                    })
                                    )
                                )
                            ).
                        append(
                            jQuery("<div>").
                            addClass("td").
                            css({
                                "width":"300px"
                            }).
                            append(
                                jQuery("<div/>").
                                html("&nbsp;").
                                css({
                                    "background-color":"#FFF",
                                    "border":"1px solid #000",
                                    "border-radius":"3px",
                                    "vertical-align":"middle",
                                    "height":"100%"
                                })
                                )
                            ).
                        append(
                            jQuery("<div>&gt;</div>").
                            addClass("td align-center").
                            css({
                                "width":"40px",
                                height:(jQuery(window).height()-110)+"px",
                                "line-height":(jQuery(window).height()-110)+"px"
                            })
                            )
                        ).
                    append(
                        jQuery("<div>").
                        addClass("tr").
                        css({
                            "height":"70px"
                        }).
                        append(
                            jQuery("<div>").
                            addClass("td").
                            css({
                                "width":"40px",
                                "height":"70px"
                            })
                            ).
                        append(
                            jQuery("<div>").
                            addClass("td").
                            append(
                                jQuery("<div/>").
                                addClass("p10t").
                                html("Pas de description").
                                css({
                                    color:"#FFF"
                                })
                                )
                            ).
                        append(
                            jQuery("<div>").
                            addClass("td").
                            css({
                                "width":"300px"
                            })
                            ).
                        append(
                            jQuery("<div>").
                            addClass("td").
                            css({
                                "width":"40px"
                            })
                            )
                        )
                    );                                    
                jQuery("body").append(overlay);
            },
            linkDelete : function (item) {
                var data = this.data('postwriter');
                if (data) {
                    $(item).parent().parent().parent().remove();
                    $('.osfPostReader.user-' + data.userId).OsfPostReader('resize');
                    var attachments = this.find('.attachment');
                    var text = this.find('.content');
                    if(text.val().length || 0 < attachments.length){
                        this.find('.content-publish').attr("disabled", false);
                    } else {
                        this.find('.content-publish').attr("disabled", true);
                    }
                }
            },
            linkCheck : function (link) {
                var data = this.data('postwriter');
                if (data && link != '') {
                    this.find('.analyse').show();
                    osf.api.link.check(link, data.userId);
                }
            },
            linkAnalyze : function (item) {
                var me = this;
                var data = this.data('postwriter');
                if (data) {
                    this.find('.analyse').hide();
                    if (item.type) {
                        if(item.type == "image"){
                            var article = jQuery("<article/>").
                            addClass("photo m5r brd2").css({
                                'width' : item.width + 'px', 
                                'text-align':'center', 
                                'background-color' : '#000', 
                                'overflow' : 'hidden'
                            });

                            var photo = jQuery("<img/>").
                            attr({
                                src:item.thumbnail
                            }).
                            addClass("cursor pointer").
                            css({
                                height: item.height + "px", 
                                'margin-left':'-50%',
                                'margin-right':'-50%'
                            }).
                            click(function(){
                                me.OsfPostWriter('mediaView',item);
                            });
                            
                            var input = jQuery("<input/>").attr({
                                name:'addPost[attachment][]',
                                value:item.id,
                                type:'hidden'
                            }).
                            addClass('attachment');

                            var remove = jQuery("<a/>").addClass("absolute bgwhite brd2b brd2l").css({
                                right:"0px",
                                top:"0px"
                            }).
                            append(jQuery("<span/>").html("&nbsp;").addClass("icon-24x24 delete3")).
                            click(function(){
                                me.OsfPostWriter('mediaDelete',this);
                            });
                            
                            article.append(input).append(photo).append(remove);
                            this.find('.gallery').addClass("brd2b");
                            this.find('.gallery .content').append(article.hide().fadeIn());  
                            this.find('.gallery .table').show();  
                            $('.osfPostReader.user-' + data.userId).OsfPostReader('resize');
                        
                            //-- Reposition content --//
                            var pos = 5;
                            var w = article.width();
                            var p = article.position();
                            p = p.left;
                            if(data.galleryWidth < p + w){
                                pos = -p -w - 5 + data.galleryWidth;
                            }
                            if(pos < 5){
                                this.find('.gallery .content').animate({
                                    left:pos+"px"
                                });
                            }
                            this.find('.content-length').parent().show();
                            $('.osfPostReader.user-' + data.userId).OsfPostReader('resize');
                        } else if(item.type == "bookmark"){
                            var article = jQuery("<article/>").
                            addClass("brd2b link");
                            article.
                            append(
                                jQuery("<header/>").
                                addClass("m0 p0").
                                append(
                                    jQuery("<h6/>").
                                    append(
                                        jQuery("<span/>").
                                        html("&nbsp;").
                                        addClass("icon-16x16 link m5l m5t")
                                        ).
                                    append(
                                        jQuery("<span/>").
                                        html(item.title == "" ? item.url : item.title).
                                        addClass("icon-24x24 texte")
                                        ).
                                    append(
                                        jQuery("<a/>").
                                        addClass("float-right").
                                        click(function(){
                                            me.OsfPostWriter('linkDelete',this);
                                        }).
                                        append(
                                            jQuery("<span/>").
                                            html("&nbsp;").
                                            addClass("icon-24x24 delete3")
                                            )
                                        )
                                    )
                                );

                            var description = jQuery("<p/>").
                            addClass("description p5l p5b");
                            if(item.description != ""){
                                description.
                                append(
                                    jQuery("<span/>").
                                    html(item.description).
                                    addClass("block")
                                    );
                            }
                            description.
                            append(
                                jQuery("<a/>").
                                html(item.url).
                                addClass("italic color1 icon-24x24 texte").
                                attr({
                                    href:item.url,
                                    target:"_blank"
                                })
                                );
                                
                            var input = jQuery("<input/>").attr({
                                name:'addPost[attachment][]',
                                value:item.id,
                                type:'hidden'
                            }).
                            addClass('attachment');
        
                            article.append(input).append(description);
                            this.find('.links').append(article);
                            this.find('.content-length').parent().show();
                            $('.osfPostReader.user-' + data.userId).OsfPostReader('resize');
                        }
                        this.find('.content-publish').attr("disabled", false);
                    } else {
                        osf.window.create({
                            title : 'Information',
                            params : '{autoOpen: false, width:300, height:100, modal: true,resizable:false}',
                            html : '<p class="p5 align-center">' + item.error + '</p>'
                        });
                    }
                }
            }
        };
        if (this['class'][method]) {
            return this['class'][method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return this['class'].init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist on jQuery.tooltip');
            return null;
        }
    }
};
