/*
 * jQuery TTF Text Rendering Plugin for converting elements into ttf rendered images
 *
 * Copyright (C) 2009 Mike Dabbs and Vinny Troia (www.curvve.com)
 *
 * Version 1.05
 *
 * This file is part of TTFGen.
 *
 * TTFGen is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * TTFGen is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with TtfGen.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Many thanks go to authors of code that we're used or derived from
 * to create TTFGen.
 */    
;(function($) {

/**
 * Chainable method for converting elements into ttf rendered images.
 *
 * @param options
 * @param callback fn invoked for each matched element before conversion
 * @param callback fn invoked for each matched element after conversion
 */
$.fn.ttfgen = function(options, f1, f2) {
	
    if (typeof options == 'function') {
        f2 = f1;
        f1 = options;
        options = {};
    }
    
    return this.each(function() {

        var o = getSettings(this, options);

        // pre-conversion callback, passes original element and fully populated options
        if (typeof f1 == 'function') f1(this, o);

        // save any  existing id and class
        var id = this.id ? (' id="'+this.id+'"') : '';
        var cls = o.cls ? (' class="' + o.cls + '"') : '';

        urltext = encodeURIComponent(o.caption);
        urltext = urltext.replace(/'/g, "%27");
        
        // build query string
		var q = '?text=' + urltext;
		q = q + '&font=' + o.font;
		q = q + '&fsize=' + o.fsize;
		q = q + '&pos=' + o.pos;
		q = q + '&leading=' + o.leading;
		if (o.margin)
			q = q + '&margin=' + encodeURIComponent(o.margin);
		if (o.trans)
			q = q + '&trans=1';
		if (o.width)
			q = q + '&width=' + o.width;
		
		// rgb must be last since we munge it depending on background stuff
		q = q + '&rgb=' + encodeURIComponent(o.bgColor) + ',' + encodeURIComponent(o.fgColor);

		// Build new img element
        var imgt = '<img' + id + cls;
        $.each(o.attrs, function(i, p) {
        	imgt += ' ' + i + '="' + p + '"';
        });
        
        if (this.alt && this.alt != '')
        	imgt += ' alt="' + this.alt.replace(/"/g, '&quot;') + '"';
        else if (o.addAlt)
        	imgt += ' alt="' + o.caption.replace(/"/g, '&quot;').replace(/\|/g, " ") + '"';
        
        if (this.title && this.title != '')
        	imgt += ' title="' + this.title.replace(/"/g, '&quot;') + '"';
        else if (o.addTitle)
        	imgt += ' title="' + o.caption.replace(/"/g, '&quot;').replace(/\|/g, " ") + '"';
        
        if (o.asBackground) {
        	// If being rendered as a background, set style, highlight colors and mouse event handlers
        	var q2 = q;
    		if (o.hiBgColor)
    			q2 = q2 + ',' + encodeURIComponent(o.hiBgColor);
    		if (o.hiFgColor)
    			q2 = q2 + ',' + encodeURIComponent(o.hiFgColor);
        	imgt += ' style="background: transparent url(' + o.src + q2 + ') no-repeat scroll 0 0"';
   			q = q + '&blank=1';
        	imgt += ' onmouseover="this.style.backgroundPosition=\'0% 100%\'" onmouseout="this.style.backgroundPosition=\'0% 0%\'"';
        }
        imgt += '>';
        
		// Create new img element
        var i = $(imgt);

        // Set img src
	    i.attr('src', o.src + q);

	    // Replace existing element with new img elements
        $(this).after(i).remove();

        // post-conversion callback, passes original element, new div element and fully populated options
        if (typeof f2 == 'function') f2(this, i[0], o);

    });
};

// global defaults; override as needed
$.fn.ttfgen.defaults = {
    font:			'arial',
    fsize:			24,
    pos:			0,
    trans:			1,
    leading:		0,
    asBackground:	false,
    bgColor:		'#ffffff', // background color
    fgColor:		'#000000',
    attrs:			{},
    src:			'/scripts/ttfgen/ttfgen.php',
    addAlt:			true,
    addTitle:		true
};


//
//  everything below here is private
//


// flatten all possible options: global defaults, meta, option obj
function getSettings(el, options) {
    options = options || {};
    var $el = $(el);
    var cls = el.className || '';

    // support metadata plugin (v1.0 and v2.0)
    var meta = $.metadata ? $el.metadata() : $.meta ? $el.data() : {};
    meta = meta || {};
    var w = meta.width  || parseInt(((cls.match(/w:(\d+)/)||[])[1]||0));
    var h = meta.height || parseInt(((cls.match(/h:(\d+)/)||[])[1]||0));

    if (w) meta.width  = w;
    if (h) meta.height = h;
    if (cls) meta.cls = cls;

    var a = $.fn.ttfgen.defaults;
    var b = options;
    var c = meta;

    var p = { params: { bgColor: options.bgColor || $.fn.ttfgen.defaults.bgColor } };
    var opts = $.extend({}, a, b, c);
    $.each(['attrs'], function(i,o) {
        opts[o] = $.extend({}, p[o] || {}, a[o] || {}, b[o] || {}, c[o] || {});
    });

    if (typeof opts.caption == 'undefined') opts.caption = $el.text();

    // make sure we have a source!
    opts.src = opts.src || $el.attr('href') || $el.attr('src') || 'unknown';
    return opts;
};


})(jQuery);

