/*
 * Protection des courriels (emailizer) 2.0 beta - jQuery Plugin
 * 
 * Copyright (c) 2010 par Matthieu Cardin - http://www.kryzalid.net
 * 
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Usage :
 *
 * $("div").emailizer();
 *
 */
(function($){  
        $.fn.emailizer = function(options) {

                var defaults = {
                    links   : true, // Remplace les balises <a>
                    text    : true, // Remplace dans le texte
                    debug   : false // Mode debug
                };

                var options = $.extend(defaults, options);

                return this.each(function() {
                        var obj = $(this);

                        // 1: Remplace les balises <a>
                        if(options.links){
                            var patt = /^\/([\w\-\.]+)\|([\w\-]+):([\w\.]{2,6})$/gi;
                            // Loop sur toutes les balises A trouvées
                            var aS = obj.find("a");
                            aS.each(function(){
                                var href = $(this).attr("href");
                                if (patt.test(href)) {
                                    $(this).attr( "href", "mailto:" + demailize(href) );
                                }
                                var texte = $(this).text();
                                if (texte.search(patt) >= 0) {
                                    $(this).text( demailize(texte) );
                                }
                            });
                        }

                        // 2: Remplace dans le texte
                        // TO DO!!!
                       /* if(options.text){
                            var patt = /(\/([\w\-\.]+)\|([\w\-]+):([\w\.]{2,6}))/gi;
                            var html = obj.html();
                            html  = html.replace(patt, "$2@$3.$4");
                            obj.html(html);
                        }*/
                });

                // /nom|domain:com
                function demailize(protected_email) {
                    var email;
                    var partsA = protected_email.split("|");
                    email = partsA[0].substr(1);
                    var partsB = partsA[1].split(":");
                    email+="@"+partsB[0]+"."+partsB[1];
                    return email;
                }
        };
})(jQuery);
