/**
 * Zfse_Safem is a class that has a purpose of encrypting
 * given email addresses to such form that cannot be parsed
 * by spam robots.
 * 
 * Zfse_Safem has a method makeSafe() which prints out the given address
 * parts.
 *
 * Usage:
 * Zfse_Safem.makeSafe('my-o','wn','e','mailaddress','Custom label', 30);
*/
var Zfse_Safem = {

	/**
	 * Renders the given email address parts forming
	 * an email link
	 *
	 * Use parameter label to provide an alternative
	 * label. If parameter is omitted, the email address is 
	 * used as a label. 
	 * 
	 * Use parameter cut to define the index, where the label
	 * should be chopped to the next new line.	 
	 */
	makeSafe : function(localStart, localEnd, domainStart, domainEnd, label, cut, containerId){
	
		var c = document.getElementById(containerId);
		if(!c) return;
		
		var a = document.createElement('a');
		var m = '';
		
		m += "mail";
		m += "to:";
		m += localStart;
		m += localEnd+'@';
		m += domainStart;
		m += domainEnd;
		
		if (!label) {
			label = localStart;
			label += localEnd;
			label += '@';
			label += domainStart;
			label += domainEnd;
		}
		else{
			label = label.replace(/&gt;/g, '>');
			label = label.replace(/&lt;/g, '<');
		}

		if(cut != null && cut != 0 && label.length > cut){
			var tmp = document.createElement('div');
			tmp.innerHTML = label;
			
			Zfse_Safem._cut(tmp, cut);
			label = tmp.innerHTML;
		}

		a.href = m;
		a.innerHTML = label;
		
		c.parentNode.insertBefore(a, c);
	},
	
	_cut : function(node, index){
		/**
		 * Cut text node if its nodeValue's length
		 * exceeds given index value.
		 */
		if(node.nodeType == 3){
			if(node.nodeValue.length > index){
				node.splitText(index);
				
				var br = document.createElement('br');
				node.parentNode.insertBefore(br, node.nextSibling);
				return 0;
			}
			else{
				return index-node.nodeValue.length;
			}
		}
		/**
		 * Loop recursively through child
		 * nodes.
		 */
		else{
			for(var i = 0; i<node.childNodes.length; i++){
				index = Zfse_Safem._cut(node.childNodes[i], index);
				if(index <= 0) break;
			}
			
			return index;
		}
	}
};

/**
 * Clear Zfse_Safem_mixItStack stack
 */
$(function(){
	if(typeof Zfse_Safem_mixItStack != 'undefined'){
		var specs;
		for(var i=0; i<Zfse_Safem_mixItStack.length; i++){
			specs = Zfse_Safem_mixItStack[i];
			Zfse_Safem.makeSafe(
				specs[0],
				specs[1],
				specs[2],
				specs[3],
				specs[4],
				false,
				specs[5]
			);
		}
	}		
});

/**
 * Provide support for old mixIt() function
 */
if(typeof mixIt == 'undefined'){
	function mixIt(begin1, begin2, end1, end2, arg, containerId){
		Zfse_Safem.makeSafe(begin1, begin2, end1, end2, arg, false, containerId);
	}
}
