/******************************
 * Email Plugin
 *
 * @returns {jQuery}
 */
$.fn.emailReplace = function() {

    if( this.is("a") ) {
        this.filter('a.mail').each(function() {
            var link = $(this);
            if( link.is('[href]') ) {
                buildEmailLink(link);
            }
        });
    } else {
        if( this.is("p") && !this.find('a').length ) {
            this.html( this.html().replace( htmlDecode( '--at--' ), '@' ) );
        }
        else {
            this.find('a').each(function() {
                var link = $(this);
                if( link.is('[href]') && link.attr('href').indexOf('--at--') > -1 ) {
                    buildEmailLink( link );
                }
            });
        }
    }

    function buildEmailLink(link) {

        link.attr( 'rel', 'nofollow' );
        var linkNoUrl = link.attr('href').split('//').pop();
        link.attr('href', 'mailto:' + linkNoUrl.replace('--at--', '@'));
        link.html( link.html().replace( htmlDecode( '&#8211;at&#8211;' ), '@' ) );
        link.html( link.html().replace( htmlDecode( '--at--' ), '@' ) );
    }

    /**
     * Decrypt html code
     * (like &#8211; back to --)
     * @access private
     */
    function htmlDecode( str_encode ) {
        return jQuery("<div/>").html(str_encode).text();
    }

    return this;
};

(function( $ ) {
    $('a.mail').emailReplace();
    $('p.mail').emailReplace();
}( jQuery ));