/*
 * jQuery charToTable plugin
 *
 * Copyright (c) 2007 Jean-Francois Hovinne - http://www.hovinne.com/
 * Dual licensed under the MIT and GPL licenses.
 */

jQuery.fn.charToTable = function(options) {

    options = jQuery.extend({
    
        requestUrl: 'chartopixels.php',
        character: ' ',
        append: true,
        tableClass: 'chartable',
        tdClass: 'pixel',
        withRgb: false,
        callback: null

    }, options);

    return(this.each( function() {

        var obj = this;
        
        if(!options.character || options.character == '')
          options.character = ' ';
        options.character = options.character.substr(0, 1);

        jQuery.getJSON(options.requestUrl, { c: options.character },
        
          function(json) {

            var html = '<table class="' + options.tableClass + '" />';
            if(options.append) jQuery(obj).append(html);
            else jQuery(obj).html(html);
            var table = jQuery(obj).find('table.'
             + options.tableClass + ':last');
            
            for (var i = 0; i < json.length; i++) {
            
                jQuery(table).append('<tr />');
                var tr = jQuery(table).find('tr:last');
                
                jQuery.each(json[i], function(j,val) {
                    
                    if(val == 0) html = '<td />';
                    else {
                        html = '<td class="' + options.tdClass;
                        if(options.withRgb) html += ' rgb-' + val;
                        html += '" />';
                    }

                    jQuery(tr).append(html);
                
                });
            }
            
            if(jQuery.isFunction(options.callback)) options.callback();
          }
        );
    }));
};
