/* PHP Image Replacement jQuery plugin*/
(function($){
	function picUrl(text, font, size, lineh, color) {
		var u = URL_DATA+'text/'+$.base64Encode([font,size,lineh,color,text].join('|')).replace('+', '_').replace('/', '-')+'!.png';
		$('<img>').attr('url', u);
		return u;
	}

	$.fn.pir = function(opts) {
		opts = $.extend({
			color : '000',
			font : '',
			wrap : false
		}, opts);
		
		return this.each(function(){
			var that = $(this), text = $.trim(that.text()), size, lineh, url1, url2;
			that.empty();
			if(text == '') {
				return true;
			}
			if(that.css('text-transform') == 'uppercase') {
				text = text.toUpperCase();
			}
			$.each(opts.wrap ? text.split(' ') : [text], function(){
				size = parseInt(that.css('font-size'), 10);
				lineh = parseInt(that.css('line-height'), 10);
				that.append(
					$('<img class="pir"/>')
						.attr('alt', this)
						.attr('src', picUrl(this, opts.font, size, lineh, opts.color))
				).append(' ');
				
				if(opts.hoverColor) {
					that.append(
						$('<img class="pir-hover"/>')
							.attr('alt', this)
							.attr('src', picUrl(this, opts.font, size, lineh, opts.hoverColor)).hide()
					);
				}
			});
			
			// Apply styles for images
			$('img', that).css('vertical-align', 'top');
			that.css('vertical-align', 'middle');
			
			// Hover color
			if(opts.hoverColor && opts.hoverColor != opts.color) {
				function over(){
					$('img.pir', that).hide();
					$('img.pir-hover', that).show();
				}
				function out(){
					$('img.pir-hover', that).hide();
					$('img.pir', that).show();
				}
				if(that.hasClass('open')) {
					over();
				} else {
					(that.closest('a').length > 0 ? that.closest('a') : that).hover(over, out);
				}
			}
		});
	};
})(jQuery);