﻿// JScript File
function $(id)
{
    return document.getElementById(id);
}

/*
 *    Gráfico Temporal Data
 *    Dados que persistem às callbacks
 */
 
 function GraficoTemporalData()
 {
    // Array 2xN - [Data formato YYYYMMDD][results]
    this.BarData = new Array();
    this.Bars = new Array();
    this.MaxResult = 0;
    
    // Datas máxima e mínima dos timedivisiongroup
    this.MinTimeShow = null;
    this.MaxTimeShow = null;
    
    // datas dos separadores
    this.LeftDate = null;
    this.RightDate = null;
 }

/*
 *    Gráfico Temporal Begin
 */

function TimeStep(){}
TimeStep.Year = "Year";
TimeStep.Month = "Month";
TimeStep.Week = "Week";
TimeStep.Day = "Day";

var Meses = new Array("Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez");
var SEPARATORWIDTH = 5;
var MINBARHEIGHT = 5;

function GraficoTemporal(id)
{
    this.Container = $(id);
    this.ContainerBorderWidth = 0;
    
    this.TimeDivision = $(id + "_timedivisiongroup");
    
    this.IsDemanding = false;
    this.OnDemandPrev = $(id + "_ondemandprev");
    this.OnDemandNext = $(id + "_ondemandnext");
    this.OnDemandRefDate = $(id + "_ondemandrefdate");
    
    this.RightSep = $(id + "_rightsep");
    this.RightSepShadow = $(id + "_rightsepshadow");
    this.RightPos = $(id + "_rightpos");
    this.LeftSep = $(id + "_leftsep");
    this.LeftSepShadow = $(id + "_leftsepshadow");
    this.LeftPos = $(id + "_leftpos");
    
    
    this.TimeStep = $(id + "_zoomlevel");
    this.MinDate = $(id + "_mindate");
    this.MaxDate = $(id + "_maxdate");
    
    this.MinSep = 0;
    
    this.ToolTip = $(id + "_tooltip");
    this.Zoom = $(id + "_zoom");
    this.ZoomIn = $(id + "_zoomin");
    this.ZoomOut = $(id + "_zoomout");
    
    this.Data = window[id + "data"];
    
    this.LeftResults = 0;
    this.RightResults = 0;
    
    this.ShowZoomOnWidth = 0;
    
    this.ScrollBarButton = $(id + "_scrollbarbutton");
    
    this.Legend = null;
    
}

// Actualiza os valores utilizados para as contas.
GraficoTemporal.prototype.UpdateTransformValues = function()
{
    this.DateSpan = this.Data.MaxTimeShow - this.Data.MinTimeShow;
    this.PixelSpan = this.TimeDivision.clientWidth;
    this.Offset = this.TimeDivision.offsetLeft;
    
    // Retirar os ondemand
    var cells = this.TimeDivision.getElementsByTagName("div");
    for (var i = 0; i < cells.length; i++)
    {
        if (cells[i].className == "ondemandpanelprev")
        {
            this.PixelSpan -= cells[i].clientWidth;
            this.Offset += cells[i].clientWidth;
        }
        else if (cells[i].className == "ondemandpanelnext")
            this.PixelSpan -= cells[i].clientWidth;
            
    }
}

GraficoTemporal.prototype.AddData = function(data)
{
    if (data == null) return;
    
    var length = this.Data.BarData.length;
    
    for ( var i = 0; i < data.length; i++)
    {
        var obj = $(this.Container.id + "_" + i);
        if (obj == null) return false;
        var newid = length + i;
        obj.id = newid;
        this.Data.BarData[newid] = data[i];
        this.Data.Bars[newid] = obj;
        if (data[i][1] > this.Data.MaxResult) this.Data.MaxResult = data[i][1];
    }
}

GraficoTemporal.prototype.UpdateBars = function() {
    var timedivision = null;
    for (var i = 0; i < this.Data.BarData.length; i++) {
        var bar = this.Data.Bars[i];

        if (bar.parentNode != timedivision) {
            timedivision = bar.parentNode;
        }

        var height = parseInt(this.Data.BarData[i][1] * this.Container.clientHeight / this.Data.MaxResult * 0.9);
        height = height > MINBARHEIGHT ? height : MINBARHEIGHT;

        bar.style.height = height + "px";
        bar.style.top = (this.Container.clientHeight - height) + "px";
    }
}

GraficoTemporal.prototype.WillMove = function(sep)
{
}

GraficoTemporal.prototype.Moving = function(sep)
{
}

GraficoTemporal.prototype.HasMoved = function(sep)
{
}

GraficoTemporal.prototype.CheckOnDemand = function()
{
    var position = Math.abs(this.TimeDivision.offsetLeft);
    
    if (!this.IsDemanding && this.OnDemandPrev != null && position < this.OnDemandPrev.clientWidth)
    {
        this.OnDemandRefDate.value = this.Data.MinTimeShow;
        setTimeout(this.Container.id  + ".LoadPrev();", 500);
        this.IsDemanding = true;
    }
    else if (!this.IsDemanding && this.OnDemandNext != null && (this.TimeDivision.clientWidth - position - this.Container.clientWidth) < this.OnDemandNext.clientWidth)
    {
        this.OnDemandRefDate.value = this.Data.MaxTimeShow;
        setTimeout(this.Container.id  + ".LoadNext();", 500);
        this.IsDemanding = true;
    }
}

GraficoTemporal.prototype.OnDemandReceived = function(timedivision, side)
{
    var tdg = this.TimeDivision;
    
    var isleft = side == 'prev';
    
    var ondemand = isleft ? this.OnDemandPrev : this.OnDemandNext;
    
    timedivision.parentNode.removeChild(timedivision);
    timedivision.id = "clones";
    timedivision.className = "timedivision";
    
    var clonedemand = ondemand.cloneNode(true);
    
    var more = isleft ? this.MorePrev : this.MoreNext;
    
    var left = parseFloat(tdg.style.left) - parseFloat(timedivision.style.width) + (more ? 0 : ondemand.clientWidth);
    
    // redefine as classes css do timedivision
    var cells = this.TimeDivision.getElementsByTagName("td");
    if (isleft)
    {
        var i = 0;
        for (i = 0; i < cells.length; i++)
            if (cells[i].className == "even" || cells[i].className == "odd")
                break;
                
        var count = cells[i].className == "even" ? 0 : 1;
        cells = timedivision.getElementsByTagName("td");
        for (i = cells.length - 1; i >= 0; i--)
            if (cells[i].className == "even" || cells[i].className == "odd")
                cells[i].className = count++ % 2 == 0 ? "odd" : "even";
    }
    else
    {
        var i = 0;
        for (i = cells.length - 1; i >= 0; i--)
            if (cells[i].className == "even" || cells[i].className == "odd")
                break;
                
        var count = cells[i].className == "even" ? 0 : 1;
        cells = timedivision.getElementsByTagName("td");
        for (i = 0; i < cells.length; i++)
            if (cells[i].className == "even" || cells[i].className == "odd")
                cells[i].className = count++ % 2 == 0 ? "odd" : "even";
    }
    
    
    ondemand.parentNode.appendChild(timedivision);
    ondemand.parentNode.removeChild(ondemand);
    
    if (isleft)
    {
        tdg.style.left = left + "px";
        this.OnDemandPrev = clonedemand;
    }
    else
        this.OnDemandNext = clonedemand;
    
    if (more)
    {
        var cell = null;
        if (isleft)
            cell = tdg.rows[0].insertCell(0);
        else
        {
            cell = document.createElement("td");
            tdg.rows[0].appendChild(cell);   
        }
            
        cell.appendChild(clonedemand);
    }
    
    this.UpdateBars();

    this.IsDemanding = false;
    EndTimeMoving();
    EndScrolling();
    
}

GraficoTemporal.prototype.PositionSeparators = function (leftdate, rightdate)
{
    this.Data.LeftDate = new Date();
    this.Data.LeftDate.setTime(leftdate);
    this.Data.RightDate = new Date();
    this.Data.RightDate.setTime(rightdate);
    
    this.UpdateDates();
    
    this.UpdateTransformValues();
    //$("log").innerHTML = "width:" + this.TimeDivision.clientWidth + " pixelspan: " + this.PixelSpan + " offset: " + this.Offset;
    
    var leftpos = Math.max(0, this.GetPositionForDate(this.Data.LeftDate) - SEPARATORWIDTH);
    var rightpos = Math.min(this.GetPositionForDate(this.Data.RightDate), this.Container.clientWidth - SEPARATORWIDTH);
    
    if (leftpos < this.Container.clientWidth && rightpos >= 0 && leftpos < rightpos)
    {
        this.PositionLeftSeparator(leftpos);
        this.LeftPos.value = leftpos;
        this.PositionRightSeparator(rightpos);
        this.RightPos.value = rightpos;
    }
    //this.PositionLeftSeparator(0);
}

GraficoTemporal.prototype.PositionLeftSeparator = function(finalpos)
{
    var current = parseInt(this.LeftSep.style.left);
    
    if (Math.abs(finalpos - current) > 2)
    {
        var dif = (finalpos - current) / 10;
        
        if (dif > 0)
            current += Math.max(2,dif);
        else
            current += Math.min(-2, dif);
        
        setTimeout(this.Container.id  + ".PositionLeftSeparator(" + finalpos + ");", 10);
    }
    else
    {
        current = finalpos;
        this.RefreshZoom();
    }
        
    this.LeftSep.style.left = current + "px";
    this.LeftSepShadow.style.width = current + "px";
}

GraficoTemporal.prototype.PositionRightSeparator = function(finalpos)
{   
    var current = parseInt(this.RightSep.style.left);
    
    if (Math.abs(finalpos - current) > 2)
    {
        var dif = (finalpos - current) / 10;
        
        if (dif > 0)
            current += Math.max(2,dif);
        else
            current += Math.min(-2, dif);
        
        setTimeout(this.Container.id  + ".PositionRightSeparator(" + finalpos + ");", 10);
    }
    else
    {
        current = finalpos;
        this.RefreshZoom();
    }
        
    this.RightSep.style.left = current + "px";
    this.RightSepShadow.style.width = (this.Container.clientWidth - current) + "px";
    this.RightSepShadow.style.left = current + "px";
}

// Faz update dos hiddenfield para que se saida a posição dos separadores no servidor
GraficoTemporal.prototype.UpdateDates = function()
{
    this.MinDate.value = this.Data.LeftDate.getFullYear() + "-" + (this.Data.LeftDate.getMonth() + 1) + "-" + this.Data.LeftDate.getDate();
    this.MaxDate.value = this.Data.RightDate.getFullYear() + "-" + (this.Data.RightDate.getMonth() + 1) + "-" + this.Data.RightDate.getDate();
}

GraficoTemporal.prototype.ResultsAtDate = function(date)
{
    if (this.Data.BarData == null) return 0;
    
    var total = 0;
    
    var mydate = new Date();
    mydate.setTime(date);
    
    var m = mydate.getMonth() + 1;
    var month = (m < 10 ? "0" : "") + m;
    var day = (mydate.getDate() < 10 ? "0" : "") + mydate.getDate();
    
    var cdate = mydate.getFullYear() + month + day;
    
    var i;
    for (i = 0; i < this.Data.BarData.length; i++)
        if (cdate > this.Data.BarData[i][0])
            total += this.Data.BarData[i][1];
        else break;
    
    return total;
}

GraficoTemporal.prototype.GetPositionForDate = function(date)
{
    if (this.Data.MinTimeShow == null || this.Data.MaxTimeShow == null) return null;
    this.UpdateTransformValues();
    
    return this.PixelSpan / this.DateSpan * (date.getTime() - this.Data.MinTimeShow) + this.Offset;
}

GraficoTemporal.prototype.GetDateForPosition = function(position, isend)
{
    if (this.Data.MinTimeShow == null || this.Data.MaxTimeShow == null) return null;
    
    this.UpdateTransformValues();

    var date = new Date();
    date.setTime((position - this.Offset) * this.DateSpan / this.PixelSpan + this.Data.MinTimeShow)
    
    //$("log").innerHTML += "<br /> datespan:" + datespan + " pixelspan:" + pixelspan + " position:" + position + " result:" + (position * datespan / pixelspan); 
    //$("log").innerHTML += "<br /> MaxDate:" + this.MaxTimeShow + " MinDate:" + this.MinTimeShow + " CurrentDate:" + Date.parse(date);
    
    if (isend)
    {
        switch(this.TimeStep.value)
        {
            case TimeStep.Year:
                date.setMonth(11);
                date.setDate(31);
                break;
            case TimeStep.Month:
                date.setDate(date.getMonthLastDay());
                break;
            case TimeStep.Week:
                var week = date.getWeek();
                date.setDate(1);
                date.setMonth(0);
                date.setDate(week * 7 + 6);
                break;
            case TimeStep.Day:
                break;
            default:
                break;
        }
    }
    else
    {
        switch(this.TimeStep.value)
        {
            case TimeStep.Year:
                date.setDate(1);
                date.setMonth(0);
                break;
            case TimeStep.Month:
                date.setDate(1);
                break;
            case TimeStep.Week:
                var week = date.getWeek();
                date.setDate(1);
                date.setMonth(0);
                date.setDate(week * 7);
                break;
            case TimeStep.Day:
                break;
            default:
                break;
        }
    }
    
    
    return date;
}

GraficoTemporal.prototype.UpdateLegend = function() {
    if (this.Legend == null) return;

    this.Legend.SetFromValue((this.Data.LeftDate.getDate() < 9 ? "0" : "") + this.Data.LeftDate.getDate() + "-" + Meses[this.Data.LeftDate.getMonth()] + "-" + this.Data.LeftDate.getFullYear());
    this.LeftResults = this.ResultsAtDate(this.Data.LeftDate);

    this.Legend.SetToValue((this.Data.RightDate.getDate() < 9 ? "0" : "") + this.Data.RightDate.getDate() + "-" + Meses[this.Data.RightDate.getMonth()] + "-" + this.Data.RightDate.getFullYear());
    this.RightResults = this.ResultsAtDate(this.Data.RightDate);

    //$("log").innerHTML += "<br />LeftRes: " + this.LeftResults + " RightResults: " + this.RightResults;

    this.Legend.SetResultsValue(this.RightResults - this.LeftResults);
}

GraficoTemporal.prototype.RefreshZoom = function() {
    var rpos = this.RightSep.offsetLeft;
    var lpos = this.LeftSep.offsetLeft;

    var showzoomout = this.TimeStep.value != TimeStep.Year;
    var showzoomin = rpos - lpos < this.ShowZoomOnWidth && this.TimeStep.value != TimeStep.Day;


    // Positions zooms
    this.ZoomIn.style.display = showzoomin ? "block" : "none";
    if (showzoomin) {
        if (showzoomout) {
            this.ZoomIn.style.left = (parseInt(this.Zoom.style.width) / 4 - parseInt(this.ZoomIn.style.width) / 2) + "px";
            this.ZoomIn.style.top = "0px";
        }
        else {
            this.ZoomIn.style.left = (parseInt(this.Zoom.style.width) / 2 - parseInt(this.ZoomIn.style.width) / 2) + "px";
            this.ZoomIn.style.top = "0px";
        }
    }

    this.ZoomOut.style.display = showzoomout ? "block" : "none";
    if (showzoomout) {
        if (showzoomin) {
            this.ZoomOut.style.left = (parseInt(this.Zoom.style.width) * 3 / 4 - parseInt(this.ZoomOut.style.width) / 2) + "px";
            this.ZoomOut.style.top = "-" + (parseInt(this.ZoomIn.style.height) + 2) + "px"; // correção da border
        }
        else {
            this.ZoomOut.style.left = (parseInt(this.Zoom.style.width) / 2 - parseInt(this.ZoomOut.style.width) / 2) + "px";
            this.ZoomOut.style.top = "0px";
        }
    }

    //$("log").innerHTML = "-" + parseInt(this.ZoomIn.style.height) + "px"; 

    if (showzoomin || showzoomout) {
        var top = findPosY(this.Container) - parseInt(this.Zoom.style.height) - 1; // correcção da border
        if (top < 0)
            top = findPosY(this.Container) + this.Container.clientHeight + 10;

        this.Zoom.style.top = top + "px";
        //this.Zoom.style.left = ((findPosX(this.RightSep) - findPosX(this.LeftSep) - parseInt(this.Zoom.style.width)) / 2 + findPosX(this.LeftSep)) + "px";
        this.Zoom.style.left = (this.Container.clientWidth / 2 - parseInt(this.Zoom.style.width) / 2) + "px";
        this.Zoom.style.display = "block";
    }
    else {
        this.Zoom.style.display = "none";
    }
}

/* Moving Separator */

var IsResizing = false;
var MovingGraph = null;
var MovingSep = null;
var PreviousPosition = 0;

function SetMovingSep(e,graph)
{
    if (IsResizing) return;
    
    var evt = window.event ? window.event : e;
    MovingSep = evt.target ? evt.target : evt.srcElement;
    MovingGraph = graph;
    PreviousPosition = MovingSep.offsetLeft - (SEPARATORWIDTH - 1) / 2; // Para ficar centrado
}

function StartMoving(e)
{
    if (MovingGraph.WillMove(MovingSep) == false)
        return false;
        
    document.onmouseup = EndMoving;
    document.onmousemove = MoveSep;
    document.onselectstart = function () { return false; };

    var systemEvent = window.event ? window.event : e;
    if (systemEvent.which) // Firefox
	    IsResizing = systemEvent.button == 0 ? true : false;  
	else
	    IsResizing = systemEvent.button == 1 ? true : false;
    
    StopBubble(e)
    
    return true;
}

function MoveSep(e)
{
    if (!IsResizing)
        return true;
    
    var systemEvent = window.event ? window.event : e;
    StopBubble(e);
    
    var position;
    
    var margin = (SEPARATORWIDTH - 1) / 2;
    
    var rpos = MovingGraph.RightSep.offsetLeft;
    var lpos = MovingGraph.LeftSep.offsetLeft;
    var cpos = findPosX(MovingGraph.Container);
    var newpos = systemEvent.clientX - cpos;
    
    var stalledpos;
    var outbounds = (newpos - margin) < 0 || (newpos + margin) > MovingGraph.Container.clientWidth;
    var crosssep;
    if (MovingSep == MovingGraph.LeftSep)
    {
        stalledpos = rpos;
        crosssep = newpos> rpos;
    }
    else
    {
        stalledpos = lpos;
        crosssep = newpos < lpos;
    }
    
    if (Math.abs(stalledpos - newpos) - MovingGraph.MinSep <= 0 || outbounds || crosssep)
    {
        position = PreviousPosition;
        MovingSep.style.left = position + "px";
    }
    else
    {
        position = newpos - margin;  // para ficar centrado
        PreviousPosition = position;
    }
    
    MovingSep.style.left = position + "px";
    
    if(MovingSep == MovingGraph.LeftSep)
    {
        MovingGraph.LeftSepShadow.style.width = (position < 0 ? 0 : position) + "px";
        MovingGraph.Data.LeftDate = MovingGraph.GetDateForPosition(position + SEPARATORWIDTH, false);
        MovingGraph.LeftPos.value = position + SEPARATORWIDTH;
    }
    else
    {
        var shadow = MovingGraph.RightSepShadow;
        var begin = position - margin + MovingSep.offsetWidth;
        shadow.style.width = (MovingGraph.Container.clientWidth - begin) + "px";
        shadow.style.left = begin + "px";
        MovingGraph.Data.RightDate = MovingGraph.GetDateForPosition(position, true);
        MovingGraph.RightPos.value = position;
    }
    
    MovingGraph.UpdateDates();
    MovingGraph.UpdateLegend();
    MovingGraph.RefreshZoom();
    
    //var log = $("log");
    //log.innerHTML = "spos: " + stalledpos + " pos:" + position + " rpos:" + rpos + " lpos:" + lpos + " dif:" + (Math.abs(stalledpos - systemEvent.clientX) - 2 * MovingGraph.RightSep.offsetWidth);
    
    MovingGraph.Moving(MovingSep);
}

function EndMoving()
{
    if (!IsResizing)
        return true;
        
    IsResizing = false;

    document.onselectstart = function () { return true; };    
        
    MovingGraph.HasMoved(MovingSep);
    return false;
}

/* Moving Separator */

/* Moving TimeDisivion */

var IsMovingTime = false;
var TimeDivisionOffset = 0;
var CursorPosition = 0;

function StartMovingTime(e, movinggraph)
{      

    if (movinggraph == null) return false;

    document.onmouseup = EndTimeMoving;
    document.onmousemove = MoveTime;
    document.onselectstart = function () { return false; };

    var systemEvent = window.event ? window.event : e;
    if (systemEvent.which) // Firefox
	    IsMovingTime = systemEvent.button == 0 ? true : false;  
	else
	    IsMovingTime = systemEvent.button == 1 ? true : false;
    
    StopBubble(e)
    
    MovingGraph = movinggraph
    TimeDivisionOffset = MovingGraph.TimeDivision.offsetLeft;
    CursorPosition = systemEvent.clientX;
    
    return true;
}

function MoveTime(e)
{
    if (!IsMovingTime)
        return true;
    
    var systemEvent = window.event ? window.event : e;
    StopBubble(e);
    
    var position = systemEvent.clientX - CursorPosition + TimeDivisionOffset;;
    if (position > 0)
    {
        position = 0;
        CursorPosition = systemEvent.clientX;
        TimeDivisionOffset = 0;
    }
    else if (position +  MovingGraph.TimeDivision.clientWidth < MovingGraph.Container.clientWidth)
    {
        position = MovingGraph.Container.clientWidth - MovingGraph.TimeDivision.clientWidth;
        TimeDivisionOffset = position;
        CursorPosition = systemEvent.clientX;
    }
    
    
    MovingGraph.TimeDivision.style.left = position + "px";
    
    MovingGraph.Data.LeftDate = MovingGraph.GetDateForPosition(MovingGraph.LeftSep.offsetLeft + SEPARATORWIDTH, false);
    MovingGraph.Data.RightDate = MovingGraph.GetDateForPosition(MovingGraph.RightSep.offsetLeft, true);
    MovingGraph.UpdateDates();
    MovingGraph.UpdateLegend();
    
    MovingGraph.UpdateScrollBarPosition();
    MovingGraph.CheckOnDemand();
}

function EndTimeMoving()
{
    if (!IsMovingTime)
        return true;
        
    IsMovingTime = false;

    document.onselectstart = function () { return true; };    
    
    return false;
}

/* Moving TimeDisivion */

/* ToolTip */

GraficoTemporal.prototype.ShowToolTip = function(sender) {
    if (IsResizing || IsMovingTime) return true;
    if (sender == null || this.Data == null) return false;

    sender.className = "databarselected";

    var x = findPosX(sender);
    var y = findPosY(sender);

    var top = y - parseInt(this.ToolTip.style.height) - 10;
    if (top < 0) {
        this.ToolTip.className = "tooltipdown";
        top = y + sender.clientHeight + 10;
    }
    else
        this.ToolTip.className = "tooltipup";

    this.ToolTip.style.left = (x - parseInt(this.ToolTip.style.width) / 2 + sender.clientWidth / 2) + "px";
    this.ToolTip.style.top = top + "px";

    var idx = parseInt(sender.id);
    var data = this.Data.BarData;

    var dtstr = data[idx][0] + ""; // para que seja uma string
    var date = new Date();
    date.setFullYear(dtstr.substr(0, 4));
    date.setMonth(dtstr.substr(4, 2) - 1);
    date.setDate(dtstr.substr(6, 2));

    switch (this.TimeStep.value) {
        case TimeStep.Year:
            this.ToolTip.innerHTML = "Ano de " + date.getFullYear() + "<br />" + data[idx][1] + " artigo" + ( data[idx][1] == "1" ? "" : "s" );
            break;
        case TimeStep.Month:
            this.ToolTip.innerHTML = Meses[date.getMonth()] + "-" + date.getFullYear() + "<br />" + data[idx][1] + " artigo" + ( data[idx][1] == "1" ? "" : "s" );
            break;
        case TimeStep.Week:
            this.ToolTip.innerHTML = "Semana  " + date.getWeek() + "<br />" + data[idx][1] + " artigo" + ( data[idx][1] == "1" ? "" : "s" );
            break;
        case TimeStep.Day:
            this.ToolTip.innerHTML = date.getDate() + "-" + Meses[date.getMonth()] + "-" + date.getFullYear() + "<br />" + data[idx][1] + " artigo" + ( data[idx][1] == "1" ? "" : "s" );
            break;
    }

    this.ToolTip.style.display = "block";
}

GraficoTemporal.prototype.HideToolTip = function(sender)
{
    if (sender == null) return false;
    this.ToolTip.style.display = "none";
    sender.className = "databar";
}


/* ToolTip */

/* ScrollBar */


GraficoTemporal.prototype.UpdateScrollBarPosition = function()
{
    if (this.ScrollBarButton == null) return;
    
    var scrollbarspan = this.Container.clientWidth - this.ScrollBarButton.clientWidth; // a barra tem a mesma largura que o container, menos a largura do botão para que ele não saida da barra
    var timedivisionspan =  this.TimeDivision.clientWidth - this.Container.clientWidth;;
    
    var l1 = findPosX(this.Container) - findPosX(this.TimeDivision);
    
    this.ScrollBarButton.style.left = (scrollbarspan /  timedivisionspan * l1) + "px";  
}

var IsMovingScrollBar = false;
var ScrollBarOffset = 0;

function StartScrolling(e, movinggraph)
{      
    if (movinggraph == null) return false;

    document.onmouseup = EndScrolling;
    document.onmousemove = MoveScrollBar;
    document.onselectstart = function () { return false; };

    var systemEvent = window.event ? window.event : e;
    /*if (systemEvent.which) // Firefox
	    IsMovingTime = systemEvent.button == 0 ? true : false;  
	else
	    IsMovingTime = systemEvent.button == 1 ? true : false;*/
    
    StopBubble(e)
    
    MovingGraph = movinggraph
    ScrollBarOffset = MovingGraph.ScrollBarButton.offsetLeft;
    CursorPosition = systemEvent.clientX;
    IsMovingScrollBar = true;
    
    return true;
}

function MoveScrollBar(e)
{
    if (!IsMovingScrollBar)
        return true;
    
    var systemEvent = window.event ? window.event : e;
    StopBubble(e);
    
    
    if (Math.abs(findPosY(MovingGraph.ScrollBarButton) + MovingGraph.ScrollBarButton.clientHeight / 2 - systemEvent.clientY) > 30)
    {   
        EndScrolling();
        return;
    }
    
    var scrollbarspan = MovingGraph.Container.clientWidth - MovingGraph.ScrollBarButton.clientWidth; // a barra tem a mesma largura que o container, menos a largura do botão para que ele não saida da barra
    var timedivisionspan =  MovingGraph.TimeDivision.clientWidth - MovingGraph.Container.clientWidth;;
    
    var position = systemEvent.clientX - CursorPosition + ScrollBarOffset;
    
    if (position < 0) position = 0;
    else if (position > scrollbarspan) position = scrollbarspan;
    
    
    MovingGraph.ScrollBarButton.style.left = position + "px";
    MovingGraph.TimeDivision.style.left = "-" + (timedivisionspan / scrollbarspan * position) + "px";
    
    MovingGraph.Data.LeftDate = MovingGraph.GetDateForPosition(MovingGraph.LeftSep.offsetLeft + SEPARATORWIDTH, false);
    MovingGraph.Data.RightDate = MovingGraph.GetDateForPosition(MovingGraph.RightSep.offsetLeft, true);
    MovingGraph.UpdateDates();
    MovingGraph.UpdateLegend();
    
    MovingGraph.CheckOnDemand();
}

function EndScrolling()
{
    if (!IsMovingScrollBar)
        return true;
        
    IsMovingScrollBar = false;

    document.onselectstart = function () { return true; };    
    return false;
}

/* ScrollBar */

/*
 *    Gráfico Temporal End
 */

findPosX = function(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
    {
	    while (obj.offsetParent)
	    {
		    curleft += obj.offsetLeft
		    obj = obj.offsetParent;
	    }
    }

    return curleft;
}

findPosY = function(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
	    while (obj.offsetParent)
	    {
		    curtop += obj.offsetTop
		    obj = obj.offsetParent;
	    }
    }

    return curtop;
}


function StopBubble(e)
{
    if (e == null) e = window.event;
    e.returnValue= false;   
    if (e.stopPropagation)
        e.stopPropagation();
    else
        e.cancelBubble= true; 
    if (e.preventDefault)
        e.preventDefault();
    document.body.focus();
}

// Format dd-mm-yyyy
function ParseDate(date)
{
    var split = date.split("-");
    return Date.UTC(split[2], split[1] - 1, split[0], 0, 0, 0);
}

Date.prototype.getMonthLastDay = function()
{
    switch(this.getMonth())
    {
        case 0: case 2: case 4: case 6: case 7: case 9: case 11:
            return 31;
        case 1:
            var bis = this.getFullYear() % 4 == 0 ? 1 : 0;
            return 28 + bis;
        default: 
            return 30;
    }
}

Date.prototype.getWeek = function()
{
    var week = this.getDayOfYear() / 7 + 1;
    if (week > 52) week = 52;
    return parseInt(week);
}

Date.prototype.getDayOfYear = function()
{
    var retval = 0;
    for (var i = 0; i < this.getMonth(); i++)
    {
        switch(i)
        {
            case 0: case 2: case 4: case 6: case 7: case 9: case 11: retval += 31; break;
            case 1:
                var bis = this.getFullYear() % 4 == 0 ? 1 : 0;
                retval += 28 + bis;
                break;
            default: retval += 30; break;
        }
    }
    
    retval += this.getDate();
    
    return retval;
}

