/**
*  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
      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) {

        // replace the symbols
        var mailAdd = pair[1];
        var mailAdd = mailAdd.replace(/\+/g,'.');
        var mailAdd = mailAdd.replace(/#/,'@');

        // build the new link
        var newLink = "mailto:" + mailAdd ;
				
				//Append any other variables onto the end of the mailto link
				if (qVars.length > 1) {
					for (x = 1; x < qVars.length; x++) {
						if (x == 1) {
							newLink += "?";
						} else {
							newLink += "&";
						}
						newLink += qVars[x];
					}
				}

        // set the href to the new mailto
        $(this).attr("href", newLink);

        // continue with the next element
        return true;

      }

    }

  });

};