/*
 * 
 * jQuery Google Charts - Table Plugin 0.9
 * 
 * $Date:2008-06-09 06:39:00 +0200 (lun, 09 giu 2008) $
 * $Rev:163 $
 * 
 * @requires
 * jGCharts Base
 * Metadata
 * Tablelib + Iterators (Greg Weber)
 * 
 * Copyright (c) 2008 Massimiliano Balestrieri
 * Examples and docs at: http://maxb.net/blog/
 * Licensed GPL licenses:
 * http://www.gnu.org/licenses/gpl.html
 *
 */

if(!window.jGCharts)
    alert("Include jGCharts Base Plugin");
 
jGCharts.Table = {
    init : function(options){
            
                
        return this.each(function(nr, el){
            
            var that = this;
        
            var _options = jQuery.extend({}, options);
            
            if(!_options.target){
               var _target = jQuery('<div class="jgchart">');
               jQuery(that).before(_target);
            }else{
               var _target = jQuery(_options.target);
            }
            
            _options = jQuery.extend(jQuery.metadata.get(that), _options);
                
            if(!_options.data)
                _options.data = jGCharts.Table.obj_to_array( jQuery.table(that).objs() );
            
            if(!_options.axis_labels)
	            _options.axis_labels = jQuery.map( jQuery(that).find("tbody > tr > th.serie"),
	                               function(th) { return jQuery(th).text(); }
	            );
	        if(!_options.legend)    
	            _options.legend = jQuery.map( jQuery(that).find("thead > tr:last > th.serie"),
	                                 function(th) { return jQuery(th).text(); }
	            );
            
            var api = new jGCharts.Api();
            var url = api.make(_options);
            
            
            var ch = jQuery('<img>')
            .attr('src', url);
            
            _target
            .append(ch);
            
        });
    },
    obj_to_array : function(obj){
        var _arr = [];
        var x = 0;
        for(o in obj){
            _arr[x] = [];
            for(z in obj[o])
                if(typeof obj[o][z] !== "undefined")
                    _arr[x].push(obj[o][z]);
                //if(obj[o][z])
                   
            x++;
        }
        return _arr;
    }   
};
jQuery.fn.jgtable = jGCharts.Table.init;