
(function($) {

    $.fn.replaceClass = function(classPrefix, className) {

        var self = this;

        if ($(this).attr('class')) {
            var classes = $(this).attr('class').split(' ');
            $(classes).each(function (idx, item) {
                if (item.startsWith(classPrefix)) {
                    $(self).removeClass(item);
                }
            });
        }

        $(this).addClass(classPrefix + className);

        return this;
    };

    $.fn.getClass = function(classPrefix) {

        var self = this;
        var result = null;

        if ($(this).attr('class')) {
            var classes = $(this).attr('class').split(' ');

            $(classes).each(function (idx, item) {
                if (item.startsWith(classPrefix)) {
                    result = item.substring(classPrefix.length);
                }
            });
        }

        return result;
    };

    $.fn.dataView = function() {

        if ($(this).data('view')) {

            var views = $(this).data('view').split(',');

            if (views.length > 1) {

                var items = new Array();

                $(views).each(function (idx, item) {
                    items.push('<li class="' + item + '"><a href="#">' + item + '</a></li>');
                });

                $(this).replaceClass('view-as-', views[0]);
                $(this).find('.co-media-view').append('<ul>' + items.join('') + '</ul>');

                $(this).find('.co-media-view li').on('click', function (event) {
                    event.preventDefault();
                    $(this).closest('[data-view]')
                        .replaceClass('view-as-', $(this).attr('class'))
                    ;
                });
            }
        }

        return this;
    };

    $.fn.mediaBrowser = function(options) {

        if ($(this).data('controller')) {
            $(this).data('object', new co.MediaBrowser(this, options));
        }

        return this;
    };

})(jQuery);

