/*
 * safeMail.js
 *
 * Copyright (c) 2010 Chris Leonello
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 */
 
 /*
  * Usage:
  *
  * $('#ptext').html(safeMail.obfuscateIt('(123) 555-1212'));
  * $('#etext').html(safeMail.makeAddress('userName', 'domainName' ['topLevelDomain', addSpanElements, 'spanClass']));
  *
  * <p>Phone: <span id="ptext">Please enable JavaScript to display</span><br />
  * Email: <a  id="etext" href="#" onclick="safeMail.handleClick(this);">Please enable JavaScript to display</a></p>
  *
  */

var safeMail = {

	obfuscateIt: function (word, spans, klass) {
		var ret = '';

		for (var i=0; i<word.length; i++) {
			c = '&#' + word.charCodeAt(i) + ';';
			if (spans && i>0 && parseInt(i/4) == i/4) {
				if (klass) {
					ret += '<span class="' + klass + '">';
				}
				else {
					ret += '<span style="display:none;">';
				}
				ret += '</span>';
			}
			ret += c;
		}
		return ret;
	},

	makeAddress: function (uname, dname, tdname, spans, klass) {
		if (arguments.length < 1) { return ''; }
		uname = uname || '';
		dname = dname || '';
		tdname = tdname || 'com';
		
		ret = safeMail.obfuscateIt(uname + '@' + dname + '.' + tdname, spans, klass);
		return ret;
	},
	
	makeLink: function (uname, dname, tdname, spans, klass) {
		return makeAddress('mailto:'+uname, dname, tdname, spans, klass);
	},

	handleClick: function (el, nomt) {
		var l='';
		if (el.nodeType) {
			l = el.innerHTML;
		}
		else if (typeof(el) == 'string') {
			l = el;
		}
		l = l.replace(/<[^>]+>[^<>]*<\/[^<>]+>/gi, '');
		if (!nomt) {
			l = 'mailto:' + l;
		}
		location.href = l;
		return false;
	},

	doMail: function (uname, dname, tdname) {
		tdname = tdname || 'com';
		return this.handleClick(uname+'@'+dname+'.'+tdname);
	}
};
