/**
 *  jquery.mailtoObsfucator
 *  Author: Karl Payne
 *  (c) 2009 Spiderscope (http://www.spiderscope.com/)
 **/

jQuery.fn.mailtoObsfucator = function(options) {

  settings = jQuery.extend({
     varName: "mt",
     varSep: "+"
  }, options);

  // loop through all the <a> tags
  return this.each( function () {

    // grab the href
    var href = $(this).attr("href");
//    var href = this.href;

    // check for a query string
    var qMarkPos = href.lastIndexOf('?');
    if(qMarkPos == -1) {
      // continue with the next iteration of the each
      return true;
    }

    // check for our special var
    var varPos = href.lastIndexOf(settings.varName + "=");
    if(varPos == -1) {
      // continue with the next iteration of the each
      return true;
    }

    // extract query string
    var queryString = href.substr(qMarkPos+1, href.length );

    // split query string into vars
    var qVars = queryString.split('&');

    // loop through all the vars
    for(var i in qVars ) {

      // split the current var into a key | value pair
      var pair = qVars[i].split('=');

      // check this is the variable we are looking for
      if(pair[0] == settings.varName) {

        // chop the variable up into its component parts
        var mtParts = pair[1].split(settings.varSep);

        // build the new link
        var newLink = "mailto:" + mtParts[0] + "@" + mtParts[1] + "." + mtParts[2];

        // set the href to the new mailto
        $(this).attr("href", newLink);
//        this.href = newLink;

        // continue with the next element
        return true;

      }

    }

  });

};
