lg = function(x) {
    var fTmp = ((Math.log(x))/(Math.log(10)));
    return (fTmp);
}

Raphael.fn.drawGrid = function (x, y, w, h, color, min, max, k) {
    color = color || "#000";
    var path = ["M", x, y, "L", x + w, y, x + w, y + h, x, y + h, x, y],
    	v = min,
    	offset = 0,
        count = max - min,
        txt = {font: '11px Fontin-Sans, Arial', fill: "#000"};

    for (var i = 0; i < count; i++) {
    	offset = Math.round( h / max * lg( v / min + 0.3) * k );
        path = path.concat(["M", x, h + y - offset, "L", x + w, h + y - offset]);

        if ( v == 1 || v == 10 ||v == 100 || v == 1000 || v == 10000 ) {
        	this.text(x - 20 , h + y - offset, v).attr(txt).toBack();
        	this.path(["M", x, h + y - offset - 1, "L", x + w, h + y - offset - 1]).attr({stroke: '#FFF'});
        }
        v += (v < 10) ? 1 : ( v < 100) ? 10 : (v < 1000) ? 100 : (v < 1000) ? 1000 : 10000;
        if ( v > max) break;
    }
    return this.path(path.join(",")).attr({stroke: color});
};

function Graph( e_type, r_type, height, width, holder_id, on_mouseover, on_mouseout ) {
    var values = [];
    var values_sum = 0;

    var labels = [];
    var labels1 = [];

    var _self = this;

    this.render = function() {
        // Draw
        var leftgutter = 30,
            bottomgutter = 50,
            topgutter = 20,
            r = Raphael(holder_id, width, height),
            txt = {font: '12px Fontin-Sans, Arial', fill: "#000"},
            // Ширина бара
            max = Math.max.apply(Math, values),
            min = Math.min.apply(Math, values),
            min_p = Math.min.apply(Math, labels),
            max_p = Math.max.apply(Math, labels);        
        var Y = (height - bottomgutter - topgutter) / max,
            X = (width - leftgutter) / ( labels.length + 1);

	// Вычисление максимального коэффициента
        var k = 5500, left = 0;
	do {
            k--;
	} while ( Math.abs( lg( max / min + 0.3) ) * Y * k > ( height - bottomgutter - 20) );
	r.drawGrid(leftgutter + X * .5, topgutter, width - leftgutter - X, height - topgutter - bottomgutter, "#333", min, max, k);

        for (var i = 0, ii = labels.length; i < ii; i++) {
            // Высота столбца
            var h = Math.round( Y * Math.abs( lg( values[i] / min + 0.3) ) * k );
            var x = Math.round(leftgutter + X * (i + .5));
            
            // Подпись внизу
            if ( ii <= 53 ) {
                r.text(x + X  / 2 , height - 24, labels[i]).attr(txt).rotate(90).toBack();
            } else {
                if (i % 2 == 0) r.text(x + X  / 2 , height - 24, labels[i]).attr(txt).rotate(90).toBack();
            }

            var color = NaN;
            if ( max_p != min_p ) {
                color = "hsb(" + ( 0.37 * ( 1 - (labels[i] - min_p)/(max_p - min_p) ) ) + ", 1, 0.65)";
            } else {
                color = "hsb(0.37, 1, 0.65)";
            }
            var bar = r.rect(x, height - bottomgutter - h, X, h)
                .attr({fill: color, stroke: "#000"})
                .mouseover(function () {
                    this.attr({stroke: "#FFF"})
                    if (on_mouseover) {
                        on_mouseover(this)
                    }
                }).mouseout(function () {
                    this.attr({stroke: "#000"})
                    if ( on_mouseout ) {
                        on_mouseout(this)
                    }
                });
            bar.value = values[i];
            bar.label = labels[i];
            if ( labels1[i] && bar.label != labels1[i] ) {
                bar.label1 = labels1[i];
                if ( parseFloat(bar.label1) > parseFloat(bar.label) ) {
                    var tmp = bar.label;
                    bar.label = bar.label1;
                    bar.label1 = tmp;
                }
            }
            bar.left = left.toFixed(0);
            left += bar.value;
            bar.right = values_sum - bar.value - bar.left;
            bar.right = bar.right.toFixed(0);
	}
        bar.right = 0;
        values = null;
        labels = null;
        labels1 = null;
    }

    this.loadData = function() {
        $.ajax({
            type: "GET",
            cache: false,
            url: '/uploads/i/charts/graph_' + e_type + '_' + r_type + '.json',
            dataType : 'json',
            success: function (data, textStatus) {
                for (var i in data) {
                     values.push(data[i][0]);
                     values_sum += data[i][0];
                     labels.push(data[i][1]);
                     if (data[i][2]) { labels1.push(data[i][2]); }
                }
                data = null;
                _self.render();
            }
        });
        return this;
    }

}


