/*
* TypeHelpers version 1.0
* Zoltan Hawryluk, Nov 24 2009.
* @see http://www.useragentman.com/blog/2009/11/29/how-to-detect-font-smoothing-using-javascript/
*
* Released under the MIT License. http://www.opensource.org/licenses/mit-license.php
*
* Works for
* - IE6+ (Windows),
* - Firefox 3.5+ (Windows, Mac, Linux),
* - Safari 4+ (Windows, Mac OS X),
* - Chrome 3.0+ (Windows).
* Opera 10.10 and under reports unknown support for font-smoothing.
*
* Modified by Christian Beier (www.beier-christian.eu) to detect the ClearType technology.
* 
* Modified by Andrew Pettican:
*  - Added a debugging mode to hasSmoothing()
*  - Detection is performed directly from this script via jQuery
*  - Detection on Windows XP or older Windows OS's combined with IE or Safari will always return false because:
*     a. the hasSmoothing() test is not 100% accurate and will not work properly in IE6/7/8 and Safari
*     b. XP does not use ClearType by default, so its highly likely that ClearType is off. (Vista and Win 7 have it on by default)
*
* Required: jQuery 1.3.x+
*
*
* METHODS
* -------
*
* hasSmoothing() returns:
* true if font smoothing is enabled
* false if font smoothing isn't enabled
* null if it cannot detect if it's on or not.
*
* addClasses() adds the following classes to the html tag:
* "hasFontSmoothing-true" if font smoothing is enabled
* "hasFontSmoothing-false" if it isn't
* "hasFontSmoothing-unknown" if it cannot detect it.
*
*/
$(document).ready(function()
{
	// Detect users which are Windows XP or older combined with IE or Safari
	// See: http://msdn.microsoft.com/en-us/library/ms537503%28VS.85%29.aspx#UATokenRef
	// NB: 'Windows NT 6.0' and 'Windows NT 6.1' represent Vista and Windows 7
	var th_user_agent = navigator.userAgent.toLowerCase();
	var th_xp_or_older_with_ie_or_safari = (
		th_user_agent.indexOf("windows ce")!=-1 || 
		th_user_agent.indexOf("windows 95")!=-1 || 
		th_user_agent.indexOf("windows 98")!=-1 || 
		th_user_agent.indexOf("windows nt 4.")!=-1 || // Win NT
		th_user_agent.indexOf("windows nt 5.")!=-1 // Win 2000 / XP / XP x64 / Server 2003
	) && (
		th_user_agent.indexOf("safari")!=-1 || 
		th_user_agent.indexOf("msie")!=-1
	);
	
	// Attempt to detect font smoothing
	// Note: 
	// We cannot reliably detect font smoothing in IE or Safari (regardless of OS). Plus, since XP disables 
	// ClearType by default, we will presume font smoothing is disabled for this combination of OS/Browser.
	var th_has_smoothing = false;
	if(!th_xp_or_older_with_ie_or_safari)
	{
		th_has_smoothing = TypeHelpers.hasSmoothing();
	}
	
	// Add the relative class based on if font smoothing was detected
	if (th_has_smoothing === true)
	{
		$('html').addClass('hasFontSmoothing-true');
	}
	else if (th_has_smoothing === false)
	{
		$('html').addClass('hasFontSmoothing-false');
	}
	else
	{
		// hasSmoothing() error (some browsers do not support the test --> IE!)
		$('html').addClass('hasFontSmoothing-unknown');
	}
	
	// Debug
	//alert(th_user_agent + '\n\n' + th_has_smoothing + ' - ' + $('html').attr('class'));
});


// TypeHelpers support function
var TypeHelpers = new function()
{
	var me = this;
	var debug_mode = false;
	
	me.hasSmoothing = function()
	{
		// IE has screen.fontSmoothingEnabled - sweet!      
		if (typeof(screen.fontSmoothingEnabled) != "undefined")
		{
			// WARNING: IE will return true if using 'standard' or 'cleartype' font smoothing here
			return screen.fontSmoothingEnabled;  
		}
		else
		{
			try
			{
				var result = false;
				
				// Create a 35x35 Canvas block.
				var canvasNode = document.createElement("canvas");
				canvasNode.width = "35";
				canvasNode.height = "35";
				
				// We must put this node into the body, otherwise
				// Safari Windows does not report correctly.
				canvasNode.style.display = "none";
				document.body.appendChild(canvasNode);
				var ctx = canvasNode.getContext("2d");
				
				// draw a black letter "O", 32px Arial.
				ctx.textBaseline = "top";
				ctx.font = "32px Arial";
				ctx.fillStyle = "black";
				ctx.strokeStyle = "black";
				ctx.fillText("O", 0, 0);
				
				// For debug
				var alpha_max = -1;
				var alpha_min = 256;
				var alpha_sum = 0;
				var alpha_points = 0;
				var alpha_inter_sum = 0;
				var alpha_inter_points = 0;
				
				// start at (8,1) and search the canvas from left to right,
				// top to bottom to see if we can find a non-black pixel. If
				// so we return true.
				for (var j = 8; j <= 32; j++)
				{
					for (var i = 1; i <= 32; i++)
					{
						var imageData = ctx.getImageData(i, j, 1, 1).data;
						var alpha = imageData[3];
						
						if (alpha != 255 && alpha !== 0 && alpha > 180)
						{
							result = true; // font-smoothing must be on if we have alpha values above 180 (excluding 255).
							
							// Live?
							if(!debug_mode)
							{
								return result;
							}
						}
						
						// Debug?
						if(debug_mode)
						{
							if (alpha != 255 && alpha !== 0)
							{
								alpha_max = Math.max(alpha_max, alpha);
								alpha_min = Math.min(alpha_min, alpha);
								alpha_inter_sum += alpha;
								alpha_inter_points++;
							}
							alpha_sum += alpha;
							alpha_points++;
						}
					}
				}
				
				// Debug?
				if(debug_mode)
				{
					var alpha_average = alpha_sum / alpha_points;
					var alpha_inter_average = alpha_inter_sum / alpha_inter_points;
					$("#debug").html("Min: '"+alpha_min+"', Max '"+alpha_max+"', Points '"+alpha_points+"', Sum '"+alpha_sum+"', Avg '"+alpha_average+"', InterAvg '"+alpha_inter_average+"'");
				}
				
				// didn't find any non-black pixels - return false.
				return result;
			}
			catch (ex)
			{
				// Something went wrong (for example, Opera cannot use the canvas fillText() method. Return null).
				return null;
			}
		}
	};
};
