(function($) {

 $.typefacejs = {
    tf: _typeface_js,

    doTransform: function(obj, css_options) {
        var $$ = $(obj);
        $.data($$[0], 'original-text', $$.text());
    
        // Apply css options
        $$.css(css_options);
        
        // Handle hover styles for link tags
        var links = [];
        if ($$.is('a')) links.push($$[0]);
        $$.find('a').each(function() {
            links.push(this);
        });
        $.each(links, function() {
            var $$ = $(this);
            var text = $$.text();
            if (!text) return;

            // Figure out hover color
            var original_color = $$.css('color');
            $$.addClass('hover');
            var color = $$.css('color');
            $$.removeClass('hover');
            if (original_color == color) return;

            // Create hidden hover span
            $$.empty();
            $('<span>'+text+'</span>').appendTo($$);
            $('<span>'+text+'</span>').addClass('typeface-hover').css('color', color).css('display', 'none').appendTo($$);            
            $$.hover(function() {
                $$.children().eq(0).hide();
                $$.children().eq(1).show();
            },
            function() {
                if ($$.hasClass('active') || 
                    $$.hasClass('ui-state-active') || 
                    $$.hasClass('.selected')) return;
                $$.children().eq(1).hide();
                $$.children().eq(0).show();
            });
        });
        
        // Call typeface to render the text canvas
        $.typefacejs.tf.replaceText($$[0]);

    },

    destroy: function(obj) {
        var $$ = $(obj);
        var text = '';
        $$.find('span.typeface-span').each(function() {            
            if ( ! $(this).parent().is('.typeface-hover') ) {
                text += $(this).text();
            }
        });        
        $$.empty().text(text);
    }
 }

 $.fn.typefacejs = function(o) {
    if (!_typeface_js) return this;

    var css_options, action = 'transform';
    if (typeof o == 'string') {
        if (o == 'destroy')
            action = o;
    } else {
        css_options = o;
    }

    return this.each(function() {
        switch (action) {
            case 'destroy':
                $.typefacejs.destroy(this);
                break;
            default:
                $.typefacejs.doTransform(this, css_options);
                break;
        }
    });
 }

})(jQuery);
