/**
 * @author: Wesam Saif <admin@text2png.com>
 * @copyright Copyright (c) 2008, text2PNG.com
 * @link http://www.text2png.com
 * @version 0.5 April 1st 2008
 * @license http://opensource.org/licenses/gpl-3.0.html GNU General Public License version 3 (GPLv3)
 */

//Configuration
// use a path relative to the page that is being viewed, not this javascript file
// you can also use absolut path
var $__processURL = "text2png/image.php";
var $__spacerImage = "text2png/images/spacer.gif";
var $__pngImagesFolder = "text2png/images/text2png/";
var $__cleanpoldimages = "text2png/cleanup.php";


// text2png object
var text2png = {
	onLoad : function(){
		return;
	},
	
	imgs_array: [],
	
	options: {
		color: '#000000',
		background: null,
		font: 'arial',
		size: 16,
		black: 0,
		bold: 0,
		italic: 0,
		line_height: null,
		angle: 0,
		text_align: 'left',
		text_decoration: 'none',
		opacity: 100,
		shadow_color: '#000000',
		shadow_distance: 0,
		shadow_blur: null,
		shadow_strength: 50,
		shadow_angle: 315
	},
	
	AJAX: function (){
		var text = "";
		var i=0, loop = text2png.imgs_array.length;
		for (i=0; i<loop; i++){
			for (p in text2png.imgs_array[i]){
				if (p != "el"){
					text += p+"="+encodeURI(text2png.imgs_array[i][p])+"\n";
				}
			}
			
			text += "\n\n";
		}
		
		
		parameters = "text="+encodeURI(text);
		
		var xmlHttp;
		try{  
			xmlHttp=new XMLHttpRequest(); 
		}
		catch (e){
			try{
				xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			}
  			catch (e){
				try{
					xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
				}
    			catch (e){
					return false;
				}
			}
		}
		
		xmlHttp.onreadystatechange=function(){
			if(xmlHttp.readyState==4) {
				eval(xmlHttp.responseText);
			}
		};
		
		xmlHttp.open("POST",$__processURL,true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", parameters.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.send(parameters);
	},
	
	AJAXReady: function(imgs, img_name){
		var i=0, loop = text2png.imgs_array.length, img,sp, h=0;
		for (i=0; i<loop; i++){
			if (!((navigator.userAgent.toLowerCase().indexOf("safari") != -1) && (text2png.imgs_array[i]['color'].length > 7))){
				img = document.createElement("img");
				
				if (window.opera){
					img.src = $__pngImagesFolder+imgs[i]['img']+".png";
				}
				else if ((document.all) && (!window.XMLHttpRequest)){
					img.src = $__spacerImage;
					img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+$__pngImagesFolder+imgs[i]['img']+".png')";
				}
				else {
					img.src = $__spacerImage;
					img.style.background = "url("+$__pngImagesFolder+img_name+") no-repeat 0px "+h+"px";
					h -= parseInt(imgs[i]['height']);
				}
				img.style.width = imgs[i]['width']+"px";
				img.style.height = imgs[i]['height']+"px";
				img.border = 0;
				img.alt = img.title = text2png.decodeHTMLEntities(text2png.imgs_array[i]['el'].innerHTML.replace(/(<([^>]+)>)/ig,"\n"));
				text2png.imgs_array[i]['el'].innerHTML = "";
				text2png.imgs_array[i]['el'].appendChild(img);
			}
		}
		
		text2png.imgs_array = [];
	},
	
	replace : function(){
		var argopt = text2png.getArgsOptions(text2png.makeArray(arguments));
		var arg = argopt.arguments;
		var opt = argopt.options;
		
		var i=0, loop = arg.length, txt='', elopt;
		for (i=0; i<loop; i++){
			if ((typeof arg[i]).toLowerCase() == "string")
				arg[i] = document.getElementById(arg[i]);
			
			if ((arg[i].innerHTML) && (arg[i].innerHTML != "")){
				var imgobj = {};
				
				if (document.all) var rpl_ln = "\n";
				else var rpl_ln = "";
				
				imgobj['text'] = arg[i].innerHTML.replace(/(<br>)|(<br \/>)|(<br\/>)|(\r)/ig, rpl_ln);
				elopt = text2png.getOptions (opt, arg[i]);
				for (p in elopt){
					if (elopt[p])
						imgobj[p] = elopt[p].toString().replace("-moz-","").replace("#","");
				}
				
				imgobj['el'] = arg[i];
				text2png.imgs_array.push(imgobj);
			}
		}
	},
	
	replaceAll: function(){
		var argopt = text2png.getArgsOptions(text2png.makeArray(arguments));
		var arg = argopt.arguments;
		var opt = argopt.options;
		
		var i = 0, loop = arg.length, chld, j=0, inloop=0;
		for (i=0; i<loop; i++){
			if ((typeof arg[i]).toLowerCase() == "string")
				arg[i] = document.getElementById(arg[i]);
			chld = arg[i].childNodes;
			inloop = chld.length;
			for (j=0; j< inloop; j++){
				if (chld[j].childNodes.length > 1){
					text2png.replaceAll(chld[j]);

				}
				else if (chld[j].childNodes.length == 1) {
					if (chld[j].childNodes[0].nodeType == 1){
						text2png.replaceAll(chld[j]);
					}
					else if (chld[j].childNodes[0].nodeType == 3) {
						text2png.replace(chld[j]);
					}
				}
			}
		}
	},
	
	replaceTags: function(){
		var argopt = text2png.getArgsOptions(text2png.makeArray(arguments));
		var arg = argopt.arguments;
		var opt = argopt.options;
		
		var i = 0, loop = arg.length, els, j=0, inloop=0;
		for (i=0; i<loop; i++){
			els = document.getElementsByTagName(arg[i]);
			inloop = els.length;
			for (j=0; j<inloop; j++){
				text2png.replace(els[j]);
			}
		}
	},
	
	makeArray: function (args){
		var i=0, loop = args.length;
		var arr = [];
		for (i=0; i<loop; i++)
			arr.push(args[i]);
		return arr;
	},
	
	getArgsOptions: function(arr){
		var lst = arr[arr.length - 1];
		if ((typeof lst) == "string")
			lst = {};
		else if (lst.tagName) 
			lst = {};
		else 
			arr.pop();
		return {'arguments':arr, 'options': lst};
	},
	
	getOptions : function(opt, el){
		var bld = 0;
		if (parseInt(text2png.getStyle('fontWeight', el)) > 400) bld = 1;
		else if (text2png.getStyle('fontWeight', el).toString().toLowerCase() == "bold") bld = 1;
		
		var itl = 0;
		if (text2png.getStyle('fontStyle', el).toString().toLowerCase() != "normal") itl = 1;
		
		var re = {
			color: (text2png.getStyle('color', el) || (opt.color || text2png.options.color)),
			bgcolor: (text2png.getStyle('backgroundColor', el) || (opt.color || text2png.options.background)),
			font: (text2png.getStyle('fontFamily', el) || (opt.font || text2png.options.font)),
			fontsize: (text2png.getStyle('fontSize', el) || (opt.size || text2png.options.size)),
			black: (opt.black || text2png.options.black),
			bold: (bld || (opt.bold || text2png.options.bold)),
			italic: (itl || (opt.italic || text2png.options.italic)),
			lineheight: (text2png.getStyle('lineHeight', el) || (opt.color || text2png.options.line_height)),
			angle: (opt.angle || text2png.options.angle),
			textalign: (text2png.getStyle('textAlign', el) || (opt.text_align || text2png.options.text_align)),
			textdecoration: (text2png.getStyle('textDecoration', el) || (opt.color || text2png.options.text_decoration)),
			scolor: (opt.shadow_color || text2png.options.shadow_color),
			sdistance: (opt.shadow_distance || text2png.options.shadow_distance),
			sblur: (opt.shadow_blur || text2png.options.shadow_blur),
			sstrength: (opt.shadow_strength || text2png.options.shadow_strength),
			sangle: (opt.shadow_angle || text2png.options.shadow_angle)
		};
		
		if ((parseInt(re.angle) != 0) && (re.bgcolor == "transparent")){
			var pnt;
			while(re.bgcolor == "transparent"){
				try {
					pnt = el.parentNode;
					re.bgcolor = (text2png.getStyle('backgroundColor', pnt) || (opt.color || text2png.options.background));
					if ((pnt.tagName.toLowerCase() == "body") && (re.bgcolor == "transparent")){
						re.bgcolor = "#ffffff";
						break;
					}
				}
				catch (e){
					re.bgcolor = "#ffffff";
					break;
				}
			}
		}
		if (re.bold != 1){
			if (parseInt(re.bold) > 400) re.bold = 1;
			else if (re.bold.toString().toLowerCase() == "bold") re.bold = 1;
			else re.bold = 0;
		}
		
		if (re.black == 1) re.bold = 1;
		if (re.italic.toString().toLowerCase() == "normal") re.italic = 0;
					
		var opc = (opt.opacity || text2png.options.opacity);
		if (opc != 100){
			opc = Math.round(((100-opc)/100)*255).toString(16);
			re.color += opc;
		}
		
		re.font = re.font.split(",")[0].replace(/'/g, '');
		if (re.fontsize.toString().toLowerCase().indexOf("px") != -1)
			re.fontsize = Math.round(parseFloat(re.fontsize) / 1.3);
		else
			re.fontsize = Math.round(parseFloat(re.fontsize));
						
		if (re.lineheight){
			if (re.lineheight.toString().toLowerCase().indexOf("px") != -1)
				re.lineheight = Math.round(parseFloat(re.lineheight) / 1.3);
			else
				re.lineheight = Math.round(parseFloat(re.lineheight));
		}
		
		if (isNaN(re.lineheight)) re.lineheight = null;
			
		re.angle = parseInt(re.angle) % 360;
		re.sdistance = parseInt(re.sdistance);
		re.sblur = parseInt(re.sblur);
		re.sstrength = parseInt(re.sstrength);
		re.sangle = parseInt(re.sangle) % 360;
		
		return re;
	},
	
	getStyle: function(property, el){
		var result = el.style[property];
		if (!result || (result == "")){
			if (document.defaultView) {
				result = document.defaultView.getComputedStyle(el, null).getPropertyValue(property.replace(/\w[A-Z]/g, function(match){
					return (match.charAt(0) + '-' + match.charAt(1).toLowerCase());
				}));
			}
			
			else if (el.currentStyle) result = el.currentStyle[property];
		}
		if ((property.toLowerCase().indexOf("color") != -1) && (result.toLowerCase().indexOf('rgb') != -1)){
			result = result.toLowerCase().replace("rgb", "");
			result = result.replace("(","");
			result = result.replace(")","");
			result = text2png.rgbToHex(result.split(","));
		}
		return result;
	},
	
	rgbToHex: function(arr){
		if (arr.length < 3) return false;
		if (arr.length == 4 && arr[3] == 0) return 'transparent';
		var hex = "";
		for (var i = 0; i < 3; i++){
			var bit = parseInt(arr[i]).toString(16);
			hex += ((bit.length == 1) ? '0' + bit : bit);
		}
		return hex;
	},
	
	decodeHTMLEntities: function(val){
		var entites = {'&quot;':'"','&amp;':'&','&lt;':'<','&gt;':'>','&copy;':'©','&nbsp;':' '};
		for (p in entites){
			val = val.replace(new RegExp(p, "gi"), entites[p]);
		}
		
		return val;
	},
	
	cleanupOld: function(){
		var xmlHttp;
		try{  
			xmlHttp=new XMLHttpRequest(); 
		}
		catch (e){
			try{
				xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			}
  			catch (e){
				try{
					xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
				}
    			catch (e){
					return false;
				}
			}
		}
		
		xmlHttp.open("GET",$__cleanpoldimages,true);
		xmlHttp.send(null);
		/*var img = document.createElement("img");
		img.src = $__cleanpoldimages;
		img.style.display = "none";
		document.body.appendChild(img);*/
	}
};

// loading the page
var $__text2png_load = function(){
	text2png.onLoad();
	setTimeout("text2png.AJAX()", 100);
};

// creating the onload event
if (window.attachEvent)
	window.attachEvent("onload",$__text2png_load);
else
	window.addEventListener("load",$__text2png_load,false);
	
if (Math.round(Math.random()*100) <= 5){
	setTimeout("text2png.cleanupOld()", 5000);
}
