textColor = '#000';

function BarSetChart(data) {

    this.container = null;
    this.hasLegend = false;
    this.chart = data;

    this.textContainerAttr = {                  // Параметры контейнера подписи
        'width' : 100,
        'paddingLeft' : 5
    };
    this.textLegendAttr = {                     // Cвойства текста - подписей каждого набора данных
        'font': '11px "Tahoma"', 
        'stroke': 'none',
        'fill' : '#666666',
        'text-anchor': 'start',
        'width' : 20,
        'fix'   : ($.browser.msie) ? 50 : 7,
        'paddingRight' : 4
    };
    this.textSignatureAttr = {                  // Cвойства текста - подписей значения набора
        'font': '10px "Tahoma"', 
        'stroke': 'none',
        'text-anchor': 'start',
        'xfix'   : ($.browser.msie) ? 15 : 5,
        'yfix'   : ($.browser.msie) ? 7 : 4
    };
    this.barAttr = {
        'height': 10,                           // Свойства одного прямоугольника
        'stroke': 'none'
    };
    this.gridAttr = {                           // Свойства координатной сетки
        'stroke-width' : '0.7',
        'stroke'    : '#cdcdcd'
    };
    
    this.barIndent   = 3;                      // Отступы по вертикали между значениями в пределах одного набора
    this.barsIndent  = 15;                      // Отступы по вертикали между соседними наборами

    this.setContainer = function(el) {
        this.container = el;
        
        var paddingLeft = 2,
            paddingTop = 10,
            paddingBottom = 10;
        
        var offset = $(el).offset();
        this.container.params = {
            'width'     : el.width() - paddingLeft,       // "Чистая ширина"
            'paddingLeft' : paddingLeft,                  // Отступы от края контейнера до контента
            'paddingTop'  : paddingTop,
            'paddingBottom' : paddingBottom,
            'borderLeft' : {
                'fill'    : '#000',
                'width' : paddingLeft
            }
        };
        
    }
    
    /**
    *   Отрисовка линейчатой диаграммы
    */
    this.draw = function() {
        this.prepare();
        switch (this.chart['answertype']) {
            case '0':
                this.drawEasy();
                break;
            case '1':
                this.drawComparison();
                if (this.hasLegend) {
                    this.drawLegend();
                }
                break;
            default:
                alert("Error data loading");
                return false;
        }
    }
    
    /**
    *   Отрисовка линейчатой диаграммы с вариантами ответа простого опроса
    */
    this.drawEasy = function() {
    
  
        // Отправной точкой в отрисовке будет координата черного бордюра
        var xPosBase = this.textContainerAttr['width'] + this.textLegendAttr['paddingRight'];
        var yPos = this.container.params['paddingTop']; 
        
        // Рисуем координатную сетку на фоне
        this.canvas.drawGrid(xPosBase, -1, this.container.params['width'] - this.textContainerAttr['width'] - 2*this.textContainerAttr['paddingLeft'], this.container.params['height']+2, 8, 1).attr(this.gridAttr);

        
        var maxBarWidth = this.container.params['width'] -this.textContainerAttr['width'] - this.textContainerAttr['paddingLeft'] - this.container.params['paddingLeft'] - this.textLegendAttr['width'] - 10; // Некрасивая поправка на знак процента
        var coefWidth = maxBarWidth/this.chart['maxData'];
        
        // Для простого опроса имеем один набор данных
        var curSet = this.chart['data'][0];      
        var curSetData = curSet['set'];
        // Рисуем набор данных
        for ( j in curSetData) {
            var xPos = xPosBase;
            // Фикс для ie>7
            if ( $.browser.msie && yPos == this.container.params['paddingTop'] ) {
                xPos += 1;
            }
            if (curSetData[j]['value']) {
                var curWidth = parseInt(curSetData[j]['value'] * coefWidth);
                this.canvas.rect(xPos, yPos, curWidth, this.barAttr['height']).attr({ fill : curSetData[j]['color']}).attr(this.barAttr);
                var txPos = xPos + curWidth + this.textSignatureAttr['xfix'],
                    tyPos = yPos + this.textSignatureAttr['yfix'] + 6;     // - поправка на размер шрифта
                this.canvas.text(txPos, tyPos, curSetData[j]['value'] + this.chart['unit']).attr(this.textSignatureAttr).attr({'fill' : textColor});    

                yPos += this.barAttr['height'] + this.barIndent;
                
                // Рисуем текстовую подпись слева от набора по произвольным координатам
                
                /*var text        = this.canvas.text(0, 0, makeNiceSignature(this.chart['legend'][j]['value'], 15, 'right')).attr(this.textLegendAttr),
                    textWidth   = text.getBBox().width,
                    textHeight   = text.getBBox().height;
                txPos = this.textContainerAttr['width'] - this.textLegendAttr['paddingRight'] - textWidth;
                //alert('width - '+textWidth+', pos - '+txPos);
                // Установлено эмпирическим путем))
                tyPos = yPos + ( textHeight )/3 - this.barAttr['height'];
                text.attr({ x : txPos, y : tyPos });*/
                var textWidth = -1,
                    textHeight = -1;
                var text        = this.canvas.text(0, 0, makeNiceSignature(this.chart['legend'][j]['value'], 15)).attr(this.textLegendAttr);
                do {
                    textWidth   = text.getBBox().width, 
                    textHeight  = text.getBBox().height;
                } while ( textWidth == -1 || textHeight == -1);
                
                txPos = xPos - this.textLegendAttr['paddingRight'];
                // Установлено эмпирическим путем))
                tyPos = yPos + ( textHeight )/3 - this.barAttr['height'];
                // И опять фиксы
                if ( this.chart['legend'][j]['value'].length < 15 ) {
                    // Если подпись в одну строку
                    tyPos += 3;
                }
                if ( $.browser.msie ) {
                    if ( parseInt($.browser.version) == 6 ) {
                        txPos -= 40;
                        tyPos += 7;
                        if ( this.chart['legend'][j]['value'].length >= 15 ) {
                            tyPos += 2;
                        }
                        text.attr({ x : txPos, y : tyPos, 'text-anchor' : 'end'});
                    }
                    else {
                        txPos -= textWidth/2;
                        text.attr({ x : txPos, y : tyPos, 'text-anchor' : 'end'});
                    }
                }
                else {
                    text.attr({ x : txPos, y : tyPos, 'text-anchor' : 'end' });
                }

            }
        }
        // Отрисовываем левую рамку диаграммы
        this.canvas.rect(xPos,0,this.container.params['width'],this.container.params['height']).attr(this.container.params['borderLeft']);
    }
    
    /**
    *   Отрисовка линейчатой диаграммы с вариантами ответа опроса со сравнением
    */
    this.drawComparison = function() {
        // Инициализируем координаты первого прямоугольника
        var yPos = this.container.params['paddingTop']; 
        var xPos = this.container.params['paddingLeft'];
        var maxBarWidth = this.container.params['width'] -this.textContainerAttr['width'] - this.textContainerAttr['paddingLeft'] - this.container.params['paddingLeft'] - this.textLegendAttr['width'];
        var coefWidth = maxBarWidth/this.chart['maxData'];
        // Рисуем координатную сетку на фоне
        this.canvas.drawGrid(0, -1, this.container.params['width'] - this.textContainerAttr['width'] - 2*this.textContainerAttr['paddingLeft'], this.container.params['height']+2, 8, 1).attr(this.gridAttr);
    
        for ( i in this.chart['data'] ) {
            var curSet = this.chart['data'][i];      
            var curSetData = curSet['set'];
            // Рисуем подпись для каждого набора
            var bufyPos = yPos;
            // Рисуем набор данных
            for ( j in curSetData) {
                if (curSetData[j]['value']) {
                    var curWidth = parseInt(curSetData[j]['value'] * coefWidth);
                    this.canvas.rect(xPos, yPos, curWidth, this.barAttr['height']).attr({ fill : curSetData[j]['color']}).attr(this.barAttr);
                    var txPos = xPos + curWidth + this.textSignatureAttr['xfix'],
                        tyPos = yPos + this.textSignatureAttr['yfix'];     // - поправка на размер шрифта
                    this.canvas.text(txPos, tyPos, curSetData[j]['value'] + this.chart['unit']).attr(this.textSignatureAttr).attr({'fill' : textColor});    
    
                    yPos += this.barAttr['height'] + this.barIndent;
                }
            }
            txPos = this.container.params['width'] - this.textContainerAttr['width'] + this.textLegendAttr['fix'] + this.container.params['paddingLeft'];
            tyPos = (yPos - bufyPos)/2 + bufyPos;

            this.canvas.text(txPos, tyPos, makeNiceSignature(curSet['value_y'])).attr(this.textLegendAttr);
            yPos += this.barsIndent;
        }
        // Отрисовываем левую рамку диаграммы
        this.canvas.rect(0,0,this.container.params['width'],this.container.params['height']).attr(this.container.params['borderLeft']);
    }
    
    this.prepare = function() {
        // Модифицируем высоту прямоугольника для простого опроса
        if ( this.chart['answertype'] == 0 ) {
            this.barAttr['height'] *= 2.5;
        }
    
        var height = 0;
        for ( i in this.chart['data'] ) {
            var curSet = this.chart['data'][i]['set'];
            height += (getArCount(curSet) * (this.barIndent + this.barAttr['height'])) + this.barsIndent;
        }
        this.container.params['height'] = height - this.barsIndent + this.container.params['paddingTop'] + this.container.params['paddingBottom'];
        do {
            this.container.height(this.container.params['height']);
        } while (!this.container.height())
        
        this.canvas = Raphael(document.getElementById($(this.container).attr('id')), this.container.params['width'], this.container.params['height']);
    }
    
    this.drawLegend = function() {
        var legend = '',
            legendCount = this.chart['legend'].length;
        for (i=0; i<legendCount;i++ )
        {
            var curLegend = this.chart['legend'][i];
            legend += '<li><div class="mark" style="background: '+curLegend['color']+';">&nbsp;</div><div class="signature">'+curLegend['value']+'</div></li>\r\n';
        }
        legend = '<ul class="chart-big-legend">\r\n'+legend+'</ul>';
        this.container.after(legend);
    }

}


/*------------------------------------------------- END BARSETCHART CLASS ----------------------------------*/

function BarChart(data) {

    this.container = null;
    this.hasLegend = false;
    this.chart = data;

    this.textContainerAttr = {                  // Параметры контейнера подписи
        'width' : 100,
        'paddingLeft' : 5
    };
    this.textLegendAttr = {                     // Cвойства текста - подписей каждого набора данных
        'font': '11px "Tahoma"', 
        'stroke': 'none',
        'fill' : '#666666',
        'text-anchor': 'start',
        'width' : 20,
        'fix'   : ($.browser.msie) ? 50 : 0
    };
    this.textSignatureAttr = {                  // Cвойства текста - подписей значения набора
        'font': '10px "Tahoma"', 
        'stroke': 'none',
        'text-anchor': 'start',
        'height' : 20,
        'yfix'   : ($.browser.msie) ? 7 : 2,
        'xfix'   :($.browser.msie) ? 9 : 0
    };
    this.barAttr = {
        'height': 10,                           // Высота одного прямоугольника
        'stroke': 'none'
    };
    
    this.barIndent   = 2;                      // Отступы по горизонтали между значениями в пределах одного набора
    this.barsIndent  = 20;                      // Отступы по вертикали между соседними наборами

    this.setContainer = function(el) {
        this.container = el;
        
        var paddingLeft = 0,
            paddingTop = 0,
            paddingBottom = 10;
        
        var offset = $(el).offset();
        this.container.params = {
            'width'     : el.width() - paddingLeft,       // "Чистая ширина"
            'paddingLeft' : paddingLeft,                  // Отступы от края контейнера до контента
            'paddingTop'  : paddingTop,
            'paddingBottom' : paddingBottom
        };
       
    }
    
    
    this.draw = function() {
        this.prepare();
        var yPos = this.container.params['paddingTop'] + this.barsIndent; 
        var maxBarWidth = this.container.params['width'] -this.textContainerAttr['width'] - this.textContainerAttr['paddingLeft'] - this.container.params['paddingLeft'] - this.textLegendAttr['width'];
        var coefWidth = maxBarWidth/100;
        for ( i in this.chart['data'] ) {
            var xPos = this.container.params['paddingLeft'];
            var curSet = this.chart['data'][i];      
            var curSetData = curSet['set'];                         // Текущий набор
            // Рисуем подпись для каждого набора
            var bufyPos = yPos;
            for ( j in curSetData ) {
                if (curSetData[j]['value']) {
                    var curWidth = parseInt(curSetData[j]['value'] * coefWidth);
                    this.canvas.rect(xPos, yPos, curWidth, this.barAttr['height']).attr({ fill : curSetData[j]['color']}).attr(this.barAttr);
                    var txPos = xPos + this.textSignatureAttr['xfix'],
                        tyPos = yPos - 7;     // - поправка на размер шрифта
                    var text = this.canvas.text(txPos, tyPos, curSetData[j]['value'] + this.chart['unit']).attr(this.textSignatureAttr).attr({'fill' : textColor});
                    // Корректируем координату текста для центрирования
                    txPos = (curWidth - text.getBBox().width)/2 + xPos;
                    text.attr({ x : txPos });
                    xPos += curWidth + this.barIndent;
                }
            }

            txPos = this.container.params['width'] - this.textContainerAttr['width'] + this.textLegendAttr['fix'] + this.container.params['paddingLeft'];
            tyPos = (yPos - bufyPos)/2 + bufyPos + this.textSignatureAttr['yfix'];   // - нехорошая поправка на размер шрифта
            this.canvas.text(txPos, tyPos, curSet['value_y']).attr(this.textLegendAttr);
            yPos += this.barsIndent + this.barAttr['height'];
        }
        
        if (this.hasLegend) {
            this.drawLegend();
        }
    }
    
    this.prepare = function() {
        var height = getArCount(this.chart['data']) * (this.barsIndent + this.barAttr['height']);
        this.container.params['height'] = height + this.container.params['paddingTop'] + this.container.params['paddingBottom'];
        do {
            this.container.height(this.container.params['height']);
        } while (!this.container.height())
        this.canvas = Raphael(document.getElementById($(this.container).attr('id')), this.container.params['width'], this.container.params['height']);
    }
    
    this.drawLegend = function() {
        var legend = '',
            legendCount = this.chart['legend'].length;
        for (i=0; i<legendCount;i++ )
        {
            var curLegend = this.chart['legend'][i];
            legend += '<li><div class="mark" style="background: '+curLegend['color']+';">&nbsp;</div><div class="signature">'+curLegend['value']+'</div></li>\r\n';
        }
        legend = '<ul class="chart-big-legend">\r\n'+legend+'</ul>';
        this.container.after(legend);
    }

}

/*------------------------------------------------- END PIE3DCHART CLASS ----------------------------------*/

function Pie3DChart(data) {

    this.container = null;
    this.hasLegend = false;
    this.chart = data;
    
    this.coef = 1;                              // Коэффициент, определяющий долю значения в пределах набора

    this.textContainerAttr = {                  // Параметры контейнера подписи
        'width' : 100,
        'paddingLeft' : 5
    };
    this.textLegendAttr = {                     // Cвойства текста - подписей каждого набора данных
        'font': '11px "Tahoma"', 
        'stroke': 'none',
        'fill' : '#666666',
        'text-anchor': 'start',
        'width' : 20
    };
    this.textSignatureAttr = {                  // Cвойства текста - подписей значения набора
        'font': '10px "Tahoma"', 
        'stroke': 'none',
        'text-anchor': 'start',
        'height' : 20,
        'leader-width' : 30,
        'yfix'   : ($.browser.msie) ? -4 : -7,
        'xfix'   : ($.browser.msie) ? 15 : 0
    };
    
    this.ellipseAttr = {
        'stroke' : 'none',
        'side-height' : 15
    };
    
    this.setContainer = function(el) {
        this.container = el;
        
        var paddingLeft = 40,
            paddingTop = 10,
            paddingBottom = 0;
        
        var offset = $(el).offset();
        this.container.params = {
            'width'     : el.width() - paddingLeft,       // "Чистая ширина"
            'paddingLeft' : paddingLeft,                  // Отступы от края контейнера до контента
            'paddingTop'  : paddingTop,
            'paddingBottom' : paddingBottom
        };
       
    }
    
    
    
    this.draw = function() {
        this.prepare();

        
        
        var rx = (this.container.params['width'] - 2*this.container.params['paddingLeft'])/2;
        var ry = rx/1.93;   // Значение константы установлено эмпирическим путем
        
        var cx = rx + this.container.params['paddingLeft'],
            cy = this.container.params['paddingTop'] + ry;
            
        
        var lsx = this.container.params['paddingLeft'],         // Left Side x
            lsy = cy,
            rsx = cx + rx,
            rsy = cy;
        
        
        //this.canvas.ellipse(cx,cy,rx,ry).attr({fill:'orange'});
        var curSet = this.chart['data'][0];
        var curSetData = curSet['set'];                         // Текущий набор
        var curSetCount = curSetData.length;                    // Количество данных в наборе
        
        
        // Рисуем переднюю грань
        
        // Эллипс - передняя грань
        this.canvas.ellipse(cx, cy + this.ellipseAttr['side-height'], rx, ry).attr({fill:'#e0e0e0', stroke:'none'});
        // Прямоугольник, за счет которого прячутся зазоры между основным эллипсом и передней гранью
        this.canvas.rect(this.container.params['paddingLeft'], cy, 2*rx, this.ellipseAttr['side-height']).attr({fill:'#e0e0e0', stroke:'none'});
        // Ребро между основным эллипслм и передней гранью
        //this.canvas.path({fill : this.ellipseAttr['edge-color'], stroke:'none'}).moveTo(cx, cy + this.ellipseAttr['edge-height']).lineTo(cx - rx, cy).arcTo(rx, ry, 0, 0, cx + rx, cy + this.ellipseAttr['edge-height']).andClose();

        var total = 0;
        // Определяем сумму всех значений набора
        for (j=0; j<curSetCount; j++) {
            if (curSetData[j]['value']) {
                total += curSetData[j]['value'];
            }
        }
        this.coef = 100/total;
        // Рисуем сектора
        var curAngle = 0;
        for (j=0; j<curSetCount; j++) {
            if (curSetData[j]['value']) {
                this.ellipseAttr['fill'] = curSetData[j]['color'];
                
                var angleplus = 3.6 * curSetData[j]['value'] * this.coef,
                    angle = curAngle + angleplus;

                var arc = this.sector(cx, cy, rx, ry, curAngle, angle, this.ellipseAttr);
                if (angle > 180 && (angle < 360 || Math.abs(angle - 360) < 0.001)) {
                    // Попадаем в нижнюю половину эллипса, раскрашиваем переднюю грань
                    if (curAngle < 180) {
                        // Начало сектора находится в верхней половине эллипса
                        var x1 = cx - rx,
                            y1 = cy;
                    }
                    else {
                        var x1 = arc.x1,
                            y1 = arc.y1;
                    }
                    var y1  = y1,
                        x2  = arc.x2,
                        y2  = arc.y2,
                        sx1 = x1,
                        sy1 = y1 + this.ellipseAttr['side-height'],
                        sx2 = x2,
                        sy2 = y2 + this.ellipseAttr['side-height'];

                    /*if (angle != 360) {
                        // Вертикальная черта, разделяющая сектора
                        this.canvas.path({stroke : 'black'}).moveTo(x2, y2).lineTo(sx2, sy2).andClose();
                    }*/
                    // Закрашиваем часть передней грани
                    this.canvas.path({fill : this.ellipseAttr['fill']}).moveTo(x1,y1).lineTo(sx1,sy1).arcTo(rx, ry, 0, 0, sx2, sy2).lineTo(x2,y2).arcTo(rx, ry, 0, 1, x1, y1).andClose();
                    this.canvas.path({fill : '#000', opacity : '0.3'}).moveTo(x1,y1).lineTo(sx1,sy1).arcTo(rx, ry, 0, 0, sx2, sy2).lineTo(x2,y2).arcTo(rx, ry, 0, 1, x1, y1).andClose();
              //      this.canvas.path({fill : '#000', opacity : '0.3'}).moveTo(x1,y1).lineTo(sx1,sy1).arcTo(rx, ry, (angleplus > 180 ? 1 : 0), 0, sx2, sy2).lineTo(x2,y2).arcTo(rx, ry, (angleplus > 180 ? 1 : 0), 1, x1, y1).andClose();
                }
                var text_position = this.leader(cx, cy, rx, ry, curAngle, angle, {'stroke': '#b0b0b0', 'stroke-width' : '0.5'});
                this.canvas.text(text_position['x'] + this.textSignatureAttr['xfix'], text_position['y'] + this.textSignatureAttr['yfix'], curSetData[j]['value'] + this.chart['unit']).attr(this.textSignatureAttr).attr({'fill' : textColor});;
                curAngle = angle;
            }
        }
        
        if (this.hasLegend) {
            this.drawLegend();
        }
    }
    
    /**
    *   Функция рисует сектор
    */
    
    this.sector = function (cx, cy, rx, ry, startAngle, endAngle, attr) {
        var rad = Math.PI / 180;
        
        // Вычисляем координаты точек окружности, ограничивающих сектор
        var x1 = cx + rx * Math.cos(-startAngle * rad),
            x2 = cx + rx * Math.cos(-endAngle * rad),
            y1 = cy + ry * Math.sin(-startAngle * rad),
            y2 = cy + ry * Math.sin(-endAngle * rad);

        if (Math.abs(x1-x2) < 0.0001 && Math.abs(y1-y2) < 0.0001) {
            // Рисуем эллипс (сектор с углом 360)
            this.canvas.ellipse(cx, cy, rx, ry).attr(attr);
        }
        else {
            // Рисуем сектор
            this.canvas.path(attr).moveTo(cx, cy).lineTo(x1, y1).arcTo(rx, ry, (endAngle - startAngle > 180 ? 1 : 0), 0, x2, y2).andClose();
        }
        
        return {x1:x1, y1:y1, x2:x2, y2:y2};
    }
    
    /**
    *   Функция рисует выноску и возвращает координаты для отрисовки текста
    */
    this.leader = function (cx, cy, rx, ry, startAngle, endAngle, attr) {
        var rad = Math.PI / 180;
        // Вычисляем угол биссектрисы сектора
        var alfa = (endAngle - startAngle)/2 + startAngle;
        
        // Вычисляем координаты точки пересечения биссектрисы и окружности
        var x0 = cx + rx * Math.cos(-alfa * rad),
            y0 = cy + ry * Math.sin(-alfa * rad);
  
        // Вычисляем смещения выноски относительно центра эллипса
        var deltax = (x0 - cx)/2,
            deltay = (y0 - cy)/2;
        
        // Вычисляем координаты точки конца выноски (удален от центра)
        // Они же являются координатами точки начала отрезка для текстовой подписи
        var xe = deltax + x0,
            ye = deltay + y0;
            
        // Поправка на площадь полотна
        if ( (xe - this.textSignatureAttr["leader-width"]) < 0 ) {
            // Выноска выходит за пределы полотна слева
            xe = this.textSignatureAttr["leader-width"];
        }
        else if ( (xe + this.textSignatureAttr["leader-width"]) > this.container.params['width'] ) {
            // Выноска выходит за пределы полотна справа
            xe = this.container.params['width'] - this.textSignatureAttr["leader-width"];
        }

        if ( (ye - this.textSignatureAttr["height"]) < 0 ) {
            // Выноска выходит за пределы полотна сверху
            ye = this.textSignatureAttr["height"];
        }
        else if ( ye > this.container.params['height'] ) {
            ye = this.container.params['width'] - attr['stroke-width']; // Поправка на толщину выноски
        }
        // Вычисляем координаты точки конца отрезка для текстовой подписи
        var yt = ye, xt, xtext = xe;
        if ( xe <= cx ) {
            // Разворачиваем текстовую подпись влево
            xt = xe - this.textSignatureAttr["leader-width"];
            // Теперь здесь хранится координата начала текста
            xtext = xt;
        }
        else {
            // Разворачиваем текстовую подпись вправо
            xt = xe + this.textSignatureAttr["leader-width"];
        }
        
        // Вычисляем координаты начала выноски
        if (y0 > cy) {
            y0 += this.ellipseAttr['side-height'];
        }
        
        this.canvas.path(attr).moveTo(x0, y0).lineTo(xe, ye).moveTo(xe, ye).lineTo(xt, yt).andClose();
        
        return {x:xtext, y:ye};
    }
    
    this.prepare = function() {
        
        this.container.params['height'] = 200;
        do {
            this.container.height(this.container.params['height']);
        } while (!this.container.height())
        
        this.canvas = Raphael(document.getElementById($(this.container).attr('id')), this.container.params['width'], this.container.params['height']);
    }
    
    this.drawLegend = function() {
        
        var legend = '',
            legendCount = this.chart['legend'].length;
        
        for (i=0; i<legendCount;i++ )
        {
            var curLegend = this.chart['legend'][i];
            legend += '<li><div class="mark" style="background: '+curLegend['color']+';">&nbsp;</div><div class="signature">'+curLegend['value']+'</div></li>\r\n';
        }
        legend = '<ul class="chart-big-legend">\r\n'+legend+'</ul>';
        this.container.after(legend);
    }

}

/*--------------------------------------------------    ----------------------------------------------------*/
function makeNiceSignature(text, max_len) {
    var i       = 0,
        count   = text.length,
        space   = -1,           // Позиция последнего найденного пробела
        start   = 0,            // Позиция начала подстроки
        outtext = "";
        
    if (undefined === max_len) {
        max_len = 15;
    }
    while (i < count) {
        if (text.charAt(i) == " ") {
            space = i;
        }
        if (!((i+1) % max_len)) {
        // Достигли допустимой длины строки
            if (i == count-1 || text.charAt(i+1) == " ") {
                // Если граница попадает на границу слова или всей строки
                outtext += text.substring(start, i+1) + "\n"; 
                start = i + 2;
                space = i + 1;
            }
            else {
                if (space > 0) {
                    
                    outtext += text.substring(start, space) + "\n"; 
                    start = space + 1;
                    space = -1;
                }
                else {
                    // Подозрительно длинное слово, обрезаем его и переносим, как получится
                    outtext += text.substring(start, i) + "-\n";
                    start = i + 1;
                }
            }
        }
        i++;
    }
    
    outtext += text.substring(start, count);
    return outtext;
}


/**
*   Отрисовка диаграммы соответствующего типа
*
*   @param integer id   Идентификатор контейнера
*/

function startChart(id) {
    var chart = eval(id);

    switch (chart['type']) {
        case '1':
            // Круговая диаграмма
            pie3d = new Pie3DChart(chart);
            pie3d.setContainer($('#'+id));
            pie3d.hasLegend = chart['legend'] ? true : false;
            pie3d.draw();
            delete pie3d;
            break;
        case '2':
            // Линейчатая диаграмма
            barset = new BarSetChart(chart);
            barset.setContainer($('#'+id));
            barset.hasLegend = chart['legend'] ? true : false;
            barset.draw();
            delete barset;
            break;
        case '3':
            // Линейчатая диаграмма с долей в общей сумме (100%)
            bar = new BarChart(chart);
            bar.setContainer($('#'+id));
            bar.hasLegend = chart['legend'] ? true : false;
            bar.draw();
            delete bar;
    }
}

/**
*   Вычисление размерности ассоциативного массива
*
*   @param array ar_input Ассоциативный массив
*/
function getArCount(ar_input) {
    var count = 0;
    for ( i in ar_input ) {
        count++;
    }
    return count;
}

$(document).ready(function() {
//    makeNiceSignature("это тестовая строка, она очень длинная", 17, 'right');
    $('div.rating-chart').each(function(){
        var $this = $(this);
        var id = $this.attr('id');
        if (id) {
            startChart(id);
        }
        
        if ( $this.attr('rel') ) {
            $this.hover(
              function () {
                $(this).addClass('hover');
              },
              function () {
                $(this).removeClass('hover');
              }
            );
        }
        
        
        $this.bind('click', function() {
            var rel = $(this).attr('rel');
            if ( rel ) {
                location.href = $(this).attr('rel');
            }
        })
    });
});

