/**
*  jquery.mailtoObsfucator
*  Author: Karl Payne
*  (c) 2009 Spiderscope (http://www.spiderscope.com/)
**/

jQuery.fn.mailtoObsfucator = function(options) {

  settings = jQuery.extend({
     varName: "mt"
  }, options);

  // loop through all the <a> tags
  return this.each( function () {

    // grab the href
    var href = $(this).attr("href");

    // check for a query string
    var qMarkPos = href.lastIndexOf('?');
    if(qMarkPos == -1) {
      // continue with the next iteration of the each loop
      return true;
    }

    // check for our special var followed by an equals sign
    var varPos = href.lastIndexOf(settings.varName + "=");
    if(varPos == -1) {
      // continue with the next iteration of the each loop
      return true;
    }

    // extract query string
    var queryString = href.substr(qMarkPos+1, href.length );

    // split query string into vars
    var qVars = queryString.split('&');

    var newLink = '';   // stores the new url
    var varCount = 0;   // flag so we only need to re-write correctly formatted urls

    // loop through all the vars
    for(var i in qVars ) {
      varCount++;
      // split the current var into a key | value pair
      var pair = qVars[i].toString().split('=');
      // check this is the variable we are looking for
      if(pair[0] == settings.varName) {
        // replace the symbols
        var mailAdd = pair[1];
        var mailAdd = mailAdd.replace(/\+/g,'.'); // all occurences of +
        var mailAdd = mailAdd.replace(/#/,'@');   // first occurence of @
        // build the new link
        newLink = "mailto:" + mailAdd ;
      // this will only fire if the first var is the one we look for
      } else if(varCount > 1) {
        // if its the second variable, it is really the first - hehe
        if(varCount == 2) {
          newLink += "?";
        } else {
          newLink += "&";
        }
        // add any other variables back onto the url such as subject= and body=
        newLink += pair.join("=");
      // if the first var isnt the one we want
      } else {
        // continue with the next link
        return true;
      }
    }

    // if we did find a link - re-write it
    if(varCount >= 1) {
      // set the href to the new mailto
      $(this).attr("href", newLink);
    }

    // continue with the next link
    return true;

  });

};
