﻿/*Purpose:      Converts mailto email addresses to the ASCII equivalent to prevent spam bots harvesting email address.
Pre-requsites:  JavaScript must be enabled
Known problems: This solution is not accessible as it requires Javascript to work. 
                No JavaScript email obfuscator is 100% foolproof, harvesters are evolving all the time, the only way to avoid spam 100% is to have a contact form.
Created by:     Kay 27/01/09*/

//Add the event fAddEvent on the window load
fAddEvent(window, "load", fMailEncrypt);

//Create the event which adds an event listener to the window
function fAddEvent(obj, evType, fn){ if(obj.addEventListener){ obj.addEventListener(evType, fn, false); return true; } else if(obj.attachEvent){ var r = obj.attachEvent("on"+evType, fn); return r; } else return false; }
 

function fMailEncrypt(){
   
    var uniString = "", hexVal, uniChar;
    var links = document.getElementsByTagName("a");
     
    for (var i = 0 ; i < links.length ; i++) {      
        var s = links[i].getAttribute("href"); 
        if (s){
            if(s.indexOf('tocontact')!=-1){
                
         for(var l = 0; l < s.length; l++){
                //Convert char to hex
                hexVal = Number(s.charCodeAt(l)).toString(16);
                //Convert to unicode by making sure hex is 4 chars long, padding with 0's if less         
                uniString += "\\" + hexVal;     
            }
                 
                links[i].setAttribute('href', uniString); 
                links[i].onclick = function() {fMailDecrypt(this);}
            }
            
        }
     
    }
     
};


function fMailDecrypt(anchor) {

    var href = anchor.getAttribute('href');  
    var unival = href.split('\\');
    var address = "";
    
    for(var i = 0; i < unival.length; ++i){
      
        if(unival[i] != ''){
            href+=unescape('%' + unival[i]);       
       }
    }
    //decrypt from format to mailto
    var address = href.replace(/.*tocontact\/([a-z0-9._%-]+)\+([a-z0-9._%-]+)\+([a-z.]+)/i,'$1' + '@' + '$2' + '.' + '$3');
  
    if (href != address) { 
        anchor.setAttribute('href','mailto:' + address);
     }; 
     
     return false;
}
