
function raphaelGraph(){}

raphaelGraph.prototype = {
	settings:{
		holderDivName: null
		,dataDivName: null
		,months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
		,showHours: false
		,showDays: false
		,showMonths: false
		,legend: 'hit'
	},

	init: function(options)
	{
		var t = this;
		$.extend(t.settings, options);
	},

	showGraph: function()
	{
		var that = this;

		var width = $('#' + that.settings.holderDivName).innerWidth();

		// Grab the data
	    var labels = [],
	        data = [];
	    $("#" + that.settings.dataDivName + " tfoot th").each(function () {
	        labels.push($(this).html());

	    });
	    $("#" + that.settings.dataDivName + " tbody td").each(function () {
	        data.push($(this).html());
	    });

		var dotSize=4,
		dotStrokeColor='#FFF',
		showHours=that.settings.showHours;
		showDays=that.settings.showDays,
		showMonths=that.settings.showMonths,
		showYears=false;


		if(showHours){
			// Show hours
			showDays=false;
			dotStrokeColor='#1378bf';
		}else if(labels.length > 60 && labels.length <= 365){
			// Show month
			showDays=false;
			showMonths=true;
			dotSize=1;
			dotStrokeColor='#1378bf';
		}else if(labels.length > 365){
			// Show year
			showDays=false;
			showYears=true;
			dotSize=1;
			dotStrokeColor='#1378bf';
		}


	    // Draw
	    var height = 200,
	        leftgutter = 30,
	        bottomgutter = 20,
	        topgutter = 20,
	        colorhue = .6 || Math.random(),
	        //color = "hsb(" + [colorhue, 1, .75] + ")",
			color = '#1378bf';
	        r = Raphael(that.settings.holderDivName, width, height),
	        txt = {"font": '12px "Arial"', stroke: "none", fill: "#456542"},
	        txt0 = {"font": '9px "Arial"', stroke: "none", fill: "#999","text-anchor":"start"},
	        txt1 = {"font": '9px "Arial"', stroke: "none", fill: "#fff"},
	        txt2 = {"font": '12px "Arial"', stroke: "none", fill: "#000"},
	        X = (width-20 - leftgutter) / (labels.length-1),
	        max = Math.max.apply(Math, data);

		// Redefinit le max pour avoir un graphique divisé en deux correcte (400-200 et non 377-188)
		var multi;
		if(max<70)
			multi = 10;
		else if(max >= 70 && max < 1000)
			multi = 100;
		else if(max >= 10000 && max < 20000)
			multi = 250;
		else if(max >= 20000 && max < 40000)
			multi = 1000;
		else
			multi = 5000;

		if(max <= 5)
			max = 5;
		else
			max = Math.ceil(max/multi)*multi;


	    var Y = (height - bottomgutter - topgutter) / max;
	    var intervalSeparatorAxeX = showMonths ? 'months' : showYears ? 'years' : 'weeks';
		var firstDate = new Date(that.getYearFromStrUsDate(labels[0]), parseInt(that.getMonthFromStrUsDate(labels[0]), 10)-1, that.getDayFromStrUsDate(labels[0]));

		r.drawGridForGraph(leftgutter, topgutter, width - leftgutter-20, height - topgutter - bottomgutter, labels.length-1, "#CCC", firstDate, intervalSeparatorAxeX, max);
	    var path = r.path({stroke: color, "stroke-width": 3, "stroke-linejoin": "round"}),
	        bgp = r.path({stroke: "none", opacity: .2, fill: color}).moveTo(leftgutter, height - bottomgutter),
	        frame = r.rect(10, 10, 120, 40, 15).attr({fill: "#FFF", stroke: "#666", "stroke-width": 2}).hide(),
	        label = [],
	        is_label_visible = false,
	        leave_timer,
	        blanket = r.set();
	    label[0] = r.text(10, 10, "24 hits").attr(txt).hide();
	    label[1] = r.text(60, 40, "22 September 2008").attr(txt1).attr({fill: color}).hide();


		var prevMonth = null;
		var prevYear = null;

	    for (var i = 0, ii = labels.length; i < ii; i++) {
	        var y = Math.round(height - bottomgutter - Y * data[i]),
	            x = Math.round(leftgutter + X * i);


			// Draw date at the bottom interval (days, months or years)
			if(showHours){
				var hour = labels[i];
				var t = r.text(x+2, height - 6, hour + ":00").attr(txt0).toBack();
				r.path({stroke: '#ccc', "stroke-width": .5, fill: '#e6f2fa'},["M", x, y, "L", x,height]);
			}else if(showDays){
				if((i-1+firstDate.getDay())%7 == 0) {// Show date every monday
					var t = r.text(x+2, height - 6, that.strUsDateToStrEuDate(labels[i])).attr(txt0).toBack();
					r.path({stroke: '#ccc', "stroke-width": .5, fill: '#e6f2fa'},["M", x, y, "L", x,height]);
				}
			}else if(showMonths){
				var thisMonth = parseInt(that.getMonthFromStrUsDate(labels[i]),10);
				if(thisMonth != prevMonth){
					var t = r.text(x+2, height - 6, that.settings.months[thisMonth-1] + " " + that.getYearFromStrUsDate(labels[i])).attr(txt0).toBack();
					r.path({stroke: '#ccc', "stroke-width": .5, fill: '#e6f2fa'},["M", x, topgutter, "L", x,height]);
				}
				prevMonth = thisMonth;
			}else if(showYears){
				var thisYear = that.getYearFromStrUsDate(labels[i]);
				if(thisYear != prevYear){
					var t = r.text(x+2, height - 6, thisYear).attr(txt0).toBack();
					r.path({stroke: '#ccc', "stroke-width": .5, fill: '#e6f2fa'},["M", x, topgutter, "L", x,height]);
				}
				prevYear = thisYear;
			}
	        bgp[i == 0 ? "lineTo" : "cplineTo"](x, y, 0);
	        path[i == 0 ? "moveTo" : "cplineTo"](x, y, 0);

			if(max > 0){
				var dot = r.circle(x, y, dotSize).attr({fill: color, stroke: dotStrokeColor});

				blanket.push(r.rect(leftgutter + X * i, 0, X, height - bottomgutter).attr({stroke: "none", fill: "#fff", opacity: 0}));
		        var rect = blanket[blanket.length - 1];
		        (function (x, y, data, lbl, dot) {
		            var timer, i = 0;
		            $(rect.node).hover(function () {
		                clearTimeout(leave_timer);
		                var newcoord = {x: x * 1 + 7.5, y: y - 19};
		                if (newcoord.x + 100 > width) {
		                    newcoord.x -= 114;
		                }
		                frame.show().animate({x: newcoord.x, y: newcoord.y}, 200 * is_label_visible);
		                label[0].attr({text: data + " " + (parseInt(data) > 1 ? that.settings.legend + 's' : that.settings.legend)}).show().animate({x: newcoord.x * 1 + 60, y: newcoord.y * 1 + 12}, 200 * is_label_visible);
		                if(showHours){
							var hour = parseInt(lbl);
							if(hour < 10) hour = "0" + hour;
							label[1].attr({text: hour + ":00"}).show().animate({x: newcoord.x * 1 + 50, y: newcoord.y * 1 + 27}, 200 * is_label_visible);
						}else{
							label[1].attr({text: that.strUsDateToStrEuDate(lbl)}).show().animate({x: newcoord.x * 1 + 50, y: newcoord.y * 1 + 27}, 200 * is_label_visible);
		                }
						dot.attr("r", 7);
		                is_label_visible = true;
		                r.safari();
		            }, function () {
		                dot.attr("r", dotSize);
		                r.safari();
		                leave_timer = setTimeout(function () {
		                    frame.hide();
		                    label[0].hide();
		                    label[1].hide();
		                    is_label_visible = false;
		                    r.safari();
		                }, 1);
		            });
		        })(x, y, data[i], labels[i], dot);
			}
			//label[i].toFront();
	    }
	    bgp.lineTo(x, height - bottomgutter).andClose();
	    frame.toFront();
	    label[0].toFront();
	    label[1].toFront();
	    blanket.toFront();

	},

	strUsDateToStrEuDate: function(strUsDate)
	{
		var t = this;
		var day = t.getDayFromStrUsDate(strUsDate);
		var month = t.settings.months[parseInt(t.getMonthFromStrUsDate(strUsDate)-1)];
		var year = t.getYearFromStrUsDate(strUsDate);

		return day + ' ' + month + ' ' + year;
	},

	getDayFromStrUsDate: function(strUsDate)
	{
		return strUsDate.substr(6, 2);
	},

	getMonthFromStrUsDate: function(strUsDate)
	{
		return strUsDate.substr(4, 2);
	},

	getYearFromStrUsDate: function(strUsDate)
	{
		return strUsDate.substr(0, 4);
	}
}
