/*
 * 
 * Benchmark plugin 1.0
 * $Date: 2008-05-23 11:32:20 +0200 (ven, 23 mag 2008) $
 * $Rev: 109 $
 * @requires jQuery v1.2.3
 * 
 * Copyright (c) 2008 Massimiliano Balestrieri
 * Examples and docs at: http://maxb.net/blog/
 * Licensed GPL licenses:
 * http://www.gnu.org/licenses/gpl.html
 *
 */

//http://www.dustindiaz.com/basement/sugar-arrays.html
Array.prototype.indexOf = function(el, start) {
    var start = start || 0;
    for ( var i=0; i < this.length; ++i ) {
        if ( this[i] === el ) {
            return i;
        }
    }
    return -1;
};

if(!window.Benchmark)
	Benchmark = {};

Benchmark = {
	show		:	false,
	start		:	false,
	finish		:	false,
	sub1		:	false,
	sub2		:	false,
	elapsed		:	false,
	flag		:	false,
	impossible	:	false,
	url			:	'http://chart.apis.google.com/chart?',
	maxv		:	0,
	maxc		:	0,
	data		:	[],
	subdata		:	[],
	labels		:	[],
	api			:	{}, 
	options 	: 	{},
	settings	:	function(options){
		Benchmark.options = jQuery.extend({
			maxc 	: 1	,//maxc : è il limite al ciclo
			args	: false	,//serie del grafico, ciclo esterno. passa parametro
			mod		: 1,	 //il benchmark salta ogni?
			prepare : false,
			clean   : true,
			type	: false
		}, options);
		
		Benchmark.maxc = Benchmark.options.maxc;
		
		if(Benchmark.options.args === false)
			Benchmark.impossible = true;
	},
	chartapi	:	function(options){
		//http://chart.apis.google.com/chart
		Benchmark.api = jQuery.extend({
			dimensions 	: "1000x300",
			chxt		: "x,y",
			chds		: "0,",
			chxr1		: "0,0,",
			chxr2		: "1,0,",
			cht			: "lc",
			labels		: "",
			chco		: "ff0000,00ff00"
		}, options);
		Benchmark.make_url();		
	},
	chart	:	function(options){
		if(Benchmark.flag === false)
			Benchmark.chartapi(options);
			
		var dim = Benchmark.api.dimensions.split("x");
		jQuery("body").append("<p>"+Benchmark.url+"</p>");
		
		jQuery("body").append('<img width="'+dim[0]+'" height="'+dim[1]+'" src="'+Benchmark.url+'" />');
	},
	make_url:	function(){
		
		Benchmark.url	+=	'chs=' 	+ Benchmark.api.dimensions 	+ '&'; 
		Benchmark.url	+=	'chxt=' + Benchmark.api.chxt 		+ '&';
		Benchmark.url	+=	'chds=' + Benchmark.api.chds 		+ Benchmark.maxv	+	'&';
		Benchmark.url	+=	'chxr='	+ Benchmark.api.chxr1 		+ Benchmark.maxc	+	'|'	+ Benchmark.api.chxr2 + Benchmark.maxv + '&';
		
		var labelsx = data = '';
		if(Benchmark.options.type == "subdata"){
			for(serie in Benchmark.subdata){
				if(Benchmark.api.cht !== "bvg")
					data += "0,"
				 
				data += Benchmark.subdata[serie].join("|") + "|";
			}
			data = data.substr(0, data.lastIndexOf("|"));
			
			//for(var x = 0;x <=  Benchmark.subdata[serie].length; x++)
			//	labelsx += x + "|";
			labelsx = "0";
		}else{
			for(serie in Benchmark.data){
				if(Benchmark.api.cht !== "bvg")
					data += "0,"
				 
				data += Benchmark.data[serie].join(",") + "|";
			}
			data = data.substr(0, data.lastIndexOf("|"));
			labelsx = '0|' 	+ Benchmark.labels.join("|")	+ '&';		
		}	
		
		Benchmark.url	+=	'chd=t:' 	+ data	+	'&';
		Benchmark.url	+=	'chl='		+ labelsx + "&";
		Benchmark.url	+=	'cht=' 		+ Benchmark.api.cht			+ '&';
		Benchmark.url	+=	'chdl=' 	+ Benchmark.api.labels.join("|") + '&';
		Benchmark.url	+=	'chco=' 	+ Benchmark.api.chco 		;
	},
	prepare :   function(p){
        jQuery('<div id="benchmark-dom'+p+'">').hide().appendTo("body");
        if(Benchmark.show)
        	jQuery('#benchmark-dom'+p).show();
	},
	serie 	:	function(p, arg){
		jQuery('#benchmark-dom'+p).append('<div id="serie-'+p + '-' + arg +' />');
	},
	append  :	function(p, arg){
        for(var x = 1;x <= p; x++){
			var a = Benchmark.options.prepare.attr("id", "test-" + p + '-' + arg + '-' + x).clone();
    		jQuery(a).appendTo('#serie-'+p+'-'+arg);
		}
	},
	clean	:	function(p, serie){
		jQuery('#serie-' + p + '-'+ serie).empty();
	},
	substart:	function(benchmarkid, serie){
		Benchmark.sub1 = new Date().getTime();
	},
	substop	:	function(benchmarkid, serie){
		Benchmark.sub2 = new Date().getTime();
		if(!Benchmark.subdata[serie])
			Benchmark.subdata[serie] = [];
		
		var elapsed = Benchmark.sub2 - Benchmark.sub1;	
		Benchmark.subdata[serie].push(elapsed);				
	},
	stop	:	function(benchmarkid, serie){
		
        Benchmark.finish = new Date().getTime();
		//console.log("FINITO");
		Benchmark.elapsed = Benchmark.finish - Benchmark.start;
		
		if(Benchmark.elapsed > Benchmark.maxv)
		    Benchmark.maxv = Benchmark.elapsed;
		
		//labels
		if(Benchmark.labels.indexOf(benchmarkid) == -1)
			Benchmark.labels.push(benchmarkid);
		
		
		//data
		if(!Benchmark.data[serie])
			Benchmark.data[serie] = [];
		
		
		Benchmark.data[serie].push(Benchmark.elapsed);
		
		
		Benchmark.start = Benchmark.elapsed = Benchmark.finish = false;
		
		if(Benchmark.options.clean)
			Benchmark.clean(benchmarkid, serie);

	},
	each	:	function(test){//test){
		
		if(Benchmark.impossibile)
			return;
		
		//console.log("inizio i benchmark");

		for(var p = 1;p <= Benchmark.maxc; p++){
			if(p % Benchmark.options.mod === 0){
			
				//console.log("benchmark " + p);
	
				if(Benchmark.options.prepare)
					Benchmark.prepare(p);
						
					//lavora sulle serie
					for(arg in Benchmark.options.args) {
						
						Benchmark.serie(p, arg);
						//console.log("inizio la serie " + arg + " di " + Benchmark.options.args[Benchmark.options.args.length -1]);
						
						
						Benchmark.append(p, arg);
						//console.log("appendo i figli " + p);
						
						//esegue init()
						test(p, arg);
						
					}
				}
		}

	},
	prefix : function(nr, serie){
        return '#benchmark-dom' + nr +' > #serie-'+ nr +'-'+ serie + '> ';
    },
	init	:	function(options, nr, serie){
		
		options = jQuery.extend({
			test 	: function(){}
		}, options);
		
		
		var container = jQuery(this);
		var size = container.size();
		
        if(nr != size)
		  alert("Error. remove class from clone");
		
        Benchmark.start = new Date().getTime();
		return jQuery(this, container).each(
			function(z){
				var that = this;
				for(func in options.test){
					Benchmark.substart(nr, serie);
					options.test[func](that, serie);//eseguita la funzione utente
					Benchmark.substop(nr, serie);
				} 
				
				if(z == (size -1))
					Benchmark.stop(nr, serie);//nr è più sicuro
			}
		);
			
	}
};	

jQuery.fn.benchmark = Benchmark.init;
