//Image Font replacement to use custom fonts on pages/
//caveat: always call safari with $(window).load not $(document).ready
(function($){
	var SCRIPT_BASE = template_directory+'/_drawFont/drawFont.php';
	var settings;
	//var query_base;
	var mapping ={
		font: 'f',
		size: 's',
		color: 'c',
		bgcolor: 'bg',
		lineHeight: 'ls',
		textTransform: 'case',
		letterSpacing: 'k',
		padding: 'p',
		rotation: 'r',
		type: 'type',
		containerWidth: 'cw'
	};
	var total_items=0;
	var rendered_items=0;
	var complete_callback=false;
	//see  defaults at bottom for options
	$.fn.drawFont = function(){
		var options={};
		for(var i=0;i<arguments.length;i++){
			if(typeof(arguments[i])==='object'){
				options=arguments[i];
			}
			if(typeof(arguments[i])==='function'){
				complete_callback=arguments[i];
			}
		}
		settings = $.extend({}, $.fn.drawFont.defaults, options);
		$.fn.drawFont._drawIt(this);

		
	};
	//function to do the replacement
	
	$.fn.drawFont._drawIt = function(self){
		total_items+=self.length;
		if(settings.postReady && settings.setVisibilityOnComplete){
			$(self).css('visibility','hidden');
		}
		self.each(function(){
			if(settings.useCSSValues){ //if this option is false, we take the values from the options parameters
				var font=$(this).css('font-family').split(/\s*,/)[0];
				if(font!==''){settings.font=font;}
				settings.color=$.fn.drawFont.toHexColor($(this).css('color'));
				var bgcolor=$(this).css('background-color');
				if(!(bgcolor==='transparent' || bgcolor.match(/rgba/))){
					settings.bgcolor=$.fn.drawFont.toHexColor(bgcolor);
				}
				else{
					settings.bgcolor=null;
				}
				var sz=parseInt($(this).css('font-size'));
				if(!isNaN(sz)){
					settings.size=sz;
				}
				settings.textTransform=$(this).css('text-transform');
				if(settings.useLetterSpacing){
					var ls=parseInt($(this).css('letter-spacing'));
					if(!isNaN(ls)){
						settings.letterSpacing=ls;
					}
				}

				if(settings.useLineHeight){
					var lh=parseInt($(this).css('line-height'));
					if(!isNaN(lh)){
						settings.lineHeight=lh;
					}
				}

				if(settings.wordWrap){
					settings.containerWidth=$(this).width();
				}
				
			}

			var qs=settings.drawFontBase+'?'+$.fn.drawFont.createQuery($(this).html());
			if(settings.fixIEPNG && settings.type=='png' && $.browser.msie && $.browser.version<7){
				//this turns on the filter for IE6
				$(this).html('<img src="'+settings.blankImageForIE+'" alt="'+$(this).html()+'" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + qs + '\', sizingMethod=\'image\')"/>');
				if(settings.setVisibilityOnComplete){
					$(this).css('visibility','visible');
					$.fn.drawFont.eventCounter();
				}

			}
			else{
				$(this).html('<img src="" alt="'+$(this).html()+'"/>');
				//this will not make it appear until the image has fully loaded
				if(settings.setVisibilityOnComplete){
					$('img',this).load((function(self){return function(e){
						$(self).css('visibility','visible');
						$.fn.drawFont.eventCounter();
						};
						
						})(this));
				}

				$('img',this).attr('src',qs);
			}
			if(!settings.setVisibilityOnComplete){
				$.fn.drawFont.eventCounter();
			}

		});
	};
	$.fn.drawFont.eventCounter = function(){
		rendered_items++;
		if(rendered_items>=(total_items-1)){
			$('body').trigger('drawFontComplete');
			if(complete_callback && typeof complete_callback == 'function'){
				complete_callback();
			}
		}
	}
	$.fn.drawFont.createQuery = function(message){
		var query_base='';
		for(var j in settings){
			if(settings[j]!==null){
				if(mapping[j]!==undefined){
					query_base+=mapping[j]+'='+escape(settings[j])+'&';
				}
			}
		}
		if($.browser.msie && $.browser.version<7){
			message=message.replace(/&(amp;)?/g,'%26');
			message=message.replace(/\'/g,'%27');
		}
		message=jQuery.trim(message);
		message=message.replace(/\s*<br\s*\/?>\s*/i,"\n");
		message=message.replace(/\s*<\/p>\s*/i,"\n");
		return 't='+encodeURIComponent(message.replace(/<\/?[^>]+>/gi, ''))+'&'+query_base;
	};
	$.fn.drawFont.toHexColor = function(color){ //crude function to parse out rgb() values to hex
		if(color.match(/^#/)){
			return color.replace(/^#/,'').toUpperCase();
		}
		else if(color.match(/^rgb\(/i)){
			var rgbvals = /rgb\((.+),(.+),(.+)\)/i.exec(color); 
			for(var i=1;i<rgbvals.length;i++){
				var n=parseInt(rgbvals[i]).toString(16);
				if(n.length===1){
					n='0'+n;
				}
				rgbvals[i]=n;
			}
			return (rgbvals[1]+rgbvals[2]+rgbvals[3]).toUpperCase();
			
		}
		return color;
	};
	$.fn.drawFont.defaults = {
		drawFontBase: SCRIPT_BASE,
		fixIEPNG: true, //automatically adds the filter to IE6 to fix transparency 
		blankImageForIE: '/_images/blank.gif', //above needs an image to work
		useCSSValues: true, //setting this to true will read all the values out of css, rather than what was passed
		//safariTimeout: 0,  //this shouldn't need to be changed, but, if safari consistently does not display properly, up this value
							//above not needed when called with window.load rather than document.ready (only needed for safari)
		font: '',
		size: 12,
		color: '000',
		bgcolor: null,
		lineSpacing: null,
		textTransform: 'none',
		letterSpacing: null,
		lineHeight: null,
		padding: null,
		rotation: null,
		type: 'png',
		wordWrap: false,  //will wrap items to fit the container
		useLineHeight: false, //will use line-height to determine lines, rather than automatically doing it
		useLetterSpacing: false,  //will send out letter spacing values, can break rendering
		setVisibilityOnComplete: true, //if this is true, it will set visibility:visible when done processing to avoid flash of non-drawFont text
		postReady: false  //if this is true, that means we are running this after page load
	};
})(jQuery);
