/* Plugin: hex_mail
 * Author: Michael Hancock 'Onykage'
 * Wesite: www.onykage.com
 * Date: October 2009
 *
 * Description:
 *      With the proliferation of spammers out there, scrapping email addresses off of web sites,
 *      this plugin for jQuery makes it easy to hide email address from spam bots.
 *     
 * Usage:
 *
 *		First you need to encode the email address.  So we do so with a php function like this:
 *         <?php
 *         function strToHex($string) {
 *             $hex='';
 *             for ($i=0; $i < strlen($string); $i++){
 *                 $hex .= dechex(ord($string[$i]));
 *             }
 *             echo strtoupper($hex);
 *         }
 *         ?>
 *      Note: I have included a function that does this:  Just follow example.html
 *
 *		Next where you want the email to appear put this:
 *         <span id="email_link"></span>
 *
 *      Next in the documents <head> put one of these jQuery functions.
 *      To use the email address as the link text:
 *          $('#email_link').safe_mail("john.doe", "domain", "com");
 *          Ouput: <a href="mailto:john.doe@domain.com">john.doe@domain.com</a>
 *
 *      To use some other text as the link text:
 *          $('#email_link').safe_mail("john.doe", "domain", "com", "This is my email link text");
 *          Ouput: <a href="mailto:john.doe@domain.com">This is my email link text</a>
 */

jQuery.fn.hex_mail = function(username, domain_name, domain_ext, link_text) {
    var conusername = DoAsciiHex(username);
    var condomain = DoAsciiHex(domain_name);
    var condomext = DoAsciiHex(domain_ext);
    var link_text;
    var email;
    var useImage = 0;
    
	if(link_text) {
		if(link_text == " ") {
			useImage = 1;
		} else {
        	link_txt = link_text;
    	}
    } else {
        link_txt = conusername + "@" + condomain + "." + condomext;
    }
    if(useImage == 1) {
    	mail_link = "<a " + "href" + "=" + "'mail" + "to" + ":" + conusername + "@" + condomain + "." + condomext +"'>";
    	jQuery(this).wrap(mail_link);
	} else {
	    mail_link = "<a " + "href" + "=" + "'mail" + "to" + ":" + conusername + "@" + condomain + "." + condomext +"'>" + link_txt +"</a>";
	    jQuery(this).append(mail_link);
    }
};

function DoAsciiHex(x) {
    hex="0123456789ABCDEF";
    almostAscii=' !"#$%&'+"'"+'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ['+'\\'+']^_`abcdefghijklmnopqrstuvwxyz{|}';
    r="";
        for(i=0;i<x.length;i++){
            let1=x.charAt(2*i);
            let2=x.charAt(2*i+1);
            val=hex.indexOf(let1)*16+hex.indexOf(let2);
            r+=almostAscii.charAt(val-32);
        }
    return r;
};
