(function ($) {

	// Responsive table
	var Table = function (element, options) {
		this.element = $(element);
        this.switched = false;

		this.options = $.extend(true, {
            'class': 'pinned',
            'wrapper': 'table-wrapper',
            'scrollable': 'table-scrollable'
		}, options);

		this.init();
	};

	Table.prototype = {

		init: function () {
			var that = this;

            if (!that.switched) {
                this.pin();
            }
		},

        pin: function () {
            var table = $('table', this.element),
                clone = table.clone();

            this.element.addClass(this.options.class);
            clone.insertAfter(table).wrap('<div class="'+ this.options.scrollable +'" />');
            table.wrap('<div class="'+ this.options.wrapper +'" />');

            this.switched = true;
        },

        unpin: function () {
            this.element.removeClass(this.options.class);
            $('.'+ this.options.wrapper +'', this.element).unwrap();
            $('.'+ this.options.scrollable +'', this.element).remove();

            this.switched = false;
        }

	};

	$.fn.table = function (options) {
		return this.each(function() {
			if (!$(this).data('table')) {
				var table = new Table(this, options);
				$(this).data('table', table);
			}
		});
	};

})(jQuery);