﻿// Author: Entropy 
// Version: 0.1

(function ($) {
    $.fn.antispam = function (options) {
        switch (options) {
            case "destroy":
                return this.each(function () {
                    $(this).unbind(".namespace");
                });
            default:
                //Set the options.
                options = $.extend({}, $.fn.antispam.defaults, options);
                return this.each(function () {
                    var email = rot47($(this).attr("data-email"));
                    $(this).replaceWith('<a href="mailto:' + email + '">' + email + '<a/>');
                });
        }
    };

    // Public defaults.
    $.fn.antispam.defaults = {
        selector: "img[data-email]"
    };

    // Private functions.

    function rotN(text, map) {
        var result = "";
        for (var i = 0; i < text.length; i++) {
            var c = text.charAt(i);
            var index = map.indexOf(c);
            if (index >= 0) {
                c = map.charAt((index + map.length / 2) % map.length);
            }
            result += c;
        }
        return result;
    }

    function rot47(text) {
        return rotN(text, "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~");
    }

    function rot13(text/*:String*/)/*:String*/{
        return text.replace(/[a-zA-Z]/g, function (c) {
            return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
        });
    };

    $(function () {
        $($.fn.antispam.defaults.selector).antispam();
    });

})(jQuery);
