﻿//====================================================================================================================

	$(document).ready(initFontReplacement);

//====================================================================================================================

	function initFontReplacement()
	{
		$('.fontReplace').each(function(index, el)
		{
			var el = $(el);
			var fontFamily = el.css('font-family');
			if (fontFamily == '') fontFamily = 'Arial';
			var fontName;
			if (fontFamily.indexOf(',') > -1) fontName = fontFamily.split(',')[0];
			else fontName = fontFamily;
			fontName = fontName.replace(/'/gi, '');
			fontName = fontName.replace(/"/gi, '');

			var fontSize = el.css('font-size');
			if (fontSize == '') fontSize = '10px';

			var fontWeight = el.css('font-weight');
			if (fontWeight == '700') fontWeight = 'bold';
			if (fontWeight == '') fontWeight = 'normal';

			var fontStyle = el.css('font-style');
			if (fontStyle == '') fontStyle = 'normal';

			var fontColour = el.css('color');
			if (fontColour == '') fontColour = 'rgb(0, 0, 0)';
			if (fontColour.indexOf('#') == 0) fontColour = fontColour.replace('#', '');
			else fontColour = rgb2hex(fontColour);
			
			var text = el.html();
			text = text.replace(/<span>/gi, '');
			text = text.replace(/<\/span>/gi, '');
			
			var imageSrc = '/scripts/fontReplace/fontReplace.ashx?text=' + escape(text);
			imageSrc += '&fontName=' + escape(fontName);
			imageSrc += '&fontSize=' + escape(fontSize);
			imageSrc += '&fontWeight=' + escape(fontWeight);
			imageSrc += '&fontStyle=' + escape(fontStyle);
			imageSrc += '&fontColour=' + escape(fontColour);
			
			var img = new Image();
			$(img).bind('load error', function()
			{
				$(this).hide();
				$('body').append($(this));
				var imgWidth = $(this).width();
				var imgHeight = $(this).height();
				$(this).remove();
				el.css('display', 'inline-block');
				el.css('vertical-align', 'bottom');
				el.css('width', imgWidth + 'px');
				el.css('height', imgHeight + 'px');
				el.html('');
				el.css('background-image', 'url(' + imageSrc + ')');
			});
			img.src = imageSrc;
		});
	}

//====================================================================================================================

	function rgb2hex(rgb)
	{
		rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
		function hex(x)
		{
			return ("0" + parseInt(x).toString(16)).slice(-2);
		}
		return hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
	}

//====================================================================================================================

