transPngBg.js 1.68 KB
function transPngBg (img, libUrl)
{
	this.img    = img;
	this.libUrl = libUrl;

	this.RGBtoHex = function (color)
	{
		color = color.replace (/^rgb\((.*)\)$/, '$1');
		color = color.replace (/ /g, '').split (',');

		return this.toHex (color[0]) +
			this.toHex (color[1]) +
			this.toHex(color[2]);
	}

	this.toHex = function (N)
	{
		if (N == null) 
			return "00";

		N = parseInt(N);
		if (N == 0 || isNaN(N))
			return "00";

		N = Math.max (0, N);
		N = Math.min (N, 255);
		N = Math.round(N);

		return "0123456789ABCDEF".charAt ((N-N % 16) / 16) +
			"0123456789ABCDEF".charAt (N % 16);
	}

	this.getImgUrl = function (posElement)
	{
		var cNames = posElement.className.split (' ');
		var color  = posElement.style.backgroundImage;
		
		// try to get the background color of the given element from class
		// ----------------------------------------------------------------
		if (color == '')
		{
			var cName;

			for (var cN in cNames)
			{
				if (cNames[cN].indexOf ('bgc') != -1)
				{
					cName = cNames[cN];
					break;
				}
			}

			loop: for (var i=0; i<document.styleSheets.length; i++)
			{
				var rules = document.styleSheets[i].cssRules;
				if (rules == null)
					rules = document.styleSheets[i].rules;

				for (var j=0; j<rules.length; j++)
				{
					var selector = rules[j].selectorText;

					if (selector.indexOf (cName) != -1)
					{
						color = rules[j].style.backgroundColor;

						if (color.indexOf ('#') != -1)
							color = color.substr (1);
						else
							color = this.RGBtoHex (color);

						break loop;
					}
				}
			}
		}
		// ----------------------------------------------------------------

		return this.libUrl + 'gd_bgMerge.php?col=' + color + '&img=' + this.img;
	}
}