//Controls Declaration
var FlexChart = typeMenu = exportToMenu = null;

//Controls Initialization
$(document).ready(function () {    
    //FlexChart = wijmo.Control.getControl("#FlexChart");
    typeMenu = wijmo.Control.getControl('#typeMenu');
    //exportToMenu = wijmo.Control.getControl('#exportToMenu');
});

//change Chart Types
function typeMenu_ItemClicked(sender) {
    sender.header = "Chart Type: <b>" + sender.selectedItem.Header + "</b>";
    FlexChart.chartType = sender.selectedItem.Header;
}

//export Chart
function exportToMenu_ItemClicked(sender) {
    exportImage(sender.selectedItem.CommandParameter);
}

// helper function to export the FlexChart to an image
function exportImage (extension) {
    if (FlexChart!=null) {
        var chart = FlexChart,//$scope.ctx.chart,
            canvas = document.createElement('canvas'),
            ctx = canvas.getContext('2d'),
            svg = chart.hostElement.querySelector('svg'),
            size = svg.getBoundingClientRect(),
            xml;

        // inline <text> styles
        textInliner(chart.hostElement);

        // set canvas height/width
        canvas.height = size.height;
        canvas.width = size.width;

        // handle rectangle fill - otherwise transparent
        ctx.fillStyle = '#fff';
        ctx.fillRect(0, 0, size.width, size.height);

        /* Perform other preprocessing if needed */

        // serialize SVG to XML
        xml = new XMLSerializer().serializeToString(svg);

        // call canvg extension method
        ctx.drawSvg(xml, 0, 0, size.width, size.height);
        canvas.toBlob(function (blob) {
            // use FileSaver.js to save the image
            saveAs(blob, 'chart.' + extension);
        });
    }
};

// external CSS is not detected when exporting
// so one must inline some/all of these styles
function textInliner(chartHost) {
    var textEls = [].slice.call(chartHost.querySelectorAll('text')),
        style;

    textEls.forEach(function (current, index, array) {
        style = window.getComputedStyle(current);
        current.style.fontSize = style.getPropertyValue('font-size');
        current.style.fontFamily = style.getPropertyValue('font-family');
        current.style.fill = style.getPropertyValue('fill');
    });
}
