var data;
var chart;
var columnChart
var programChartData = new Array();
var query;
var chartID = 0;
var reqId = 0;
var div_container;
var div_columnChart
var dataInitSourceURL;
var dataCompSourceURL;
var initProgram;
var refProgram;

var callColumnChart;
var program1Name;
var program1VAMI;
var program2Name;
var program2VAMI;


var chartType;


//To trim out white spaces
String.prototype.trim = function () {

    return this.replace(/^\s+|\s+$/g, '');
}

//Convert ASCII code to character
String.prototype.asciiDecode = function () {

    return this.replace(/&#(\d+);/g, function (m, n) {
        return String.fromCharCode(n);
    })
}

//Remove ASCII code
String.prototype.asciiRemove = function () {

    return this.replace(/&#(\d+);/g, '');
}

// To round number with decipal point
// @param decimal = number of decimal place
// @param suffix
Number.prototype.formatNumber = function (decimal, suffix) {

    var num = this.toFixed(decimal);

    if (suffix != null || suffix != '') num = num + suffix;

    return num;
}


function initGoogleViz(siteURL, initData, refProgram, annotedChartDIV, setColumnChart, chartKind) {

    //$("#id_compare").css("display", "none");
    //$(".aclist-data").css("display", "none");

    $("#chartname").text("Cumulative Returns");
    $("#" + div_container).html("");
    $("#id_compare").css("display", "inherit");
    $(".aclist-data").css("display", "inherit");

    dataInitSourceURL = siteURL + 'DesktopModules/IASGGroups/Services/ProgramGraphData.aspx?pid='
    //'ajax/programs/getprogramPFM/';
    dataCompSourceURL = siteURL + 'DesktopModules/IASGGroups/Services/ProgramGraphData.aspx?pid='
    //'ajax/programs/getNormalizedprogramPFM/';
    initProgram = initData;
    refProgram = refProgram;
    div_container = annotedChartDIV;
    callColumnChart = setColumnChart;
    chartType = chartKind;

    google.load('visualization', '1', { 'packages': ['annotatedtimeline', 'columnchart'] });
    //google.setOnLoadCallback(initChart);
    
    
    //$("#" + div_container).load(dataCompSourceURL + initProgram + '&t=AUM');


    //chart = new google.visualization.AnnotatedTimeLine(document.getElementById(div_container));
    //drawChart(chartID - 1);



}

function initComparisonColumnChart(setProgram1Name, setProgram1VAMI, setProgram2Name, setProgram2VAMI, setDiv_columnChart) {

    if (setProgram1VAMI == '' || setProgram1VAMI == null) setProgram1VAMI = 0;
    if (setProgram2VAMI == '' || setProgram2VAMI == null) setProgram2VAMI = 0;

    program1Name = setProgram1Name;
    program1VAMI = parseFloat(setProgram1VAMI);
    program2Name = setProgram2Name;
    program2VAMI = parseFloat(setProgram2VAMI);
    div_columnChart = setDiv_columnChart;
}

function initChart() {
    pfmDataURL = dataInitSourceURL + initProgram + '&c=' + reqId // + '&t=' + chartType; //+'/'+chartID;
    chart = new google.visualization.AnnotatedTimeLine(document.getElementById(div_container));

    new google.visualization.Query(pfmDataURL + '&t=CR', 'xhr').
  send(function (response) {
      if (response.isError()) {
          //Display error message
          if ($("#" + div_container).length) {
              $("#" + div_container).css({ 'background': 'none', 'margin-top': '15px', 'padding': '15px 0', 'height': '15px', 'color': 'red' });
              $("#" + div_container).html(response.getMessage());
          }
          // Disable Auto complete Comparision, but need to check if the oject exists
          if ($("#programStatsRatioAutoCompDIV").length) $("#programStatsRatioAutoCompDIV").hide();
          if ($("#programChartAutoCompDIV").length) $("#programChartAutoCompDIV").hide();
          return;
      } else {

          data = response.getDataTable();
          programChartData[chartID] = data.clone();
          drawChart(chartID);
          chartID++;
          reqId++;
      }
  });
}

function drawChart(id) {

    var alphaValue = 0;

    if (!id) alphaValue = 55;
    /*if (id != initProgram) {
    alphaValue = 55
    }*/
    chart.draw(programChartData[id], { displayAnnotations: true,
        displayRangeSelector: false, scaleType: 'maximize', fill: alphaValue, wmode: 'transparent', displayZoomButtons: false
    }
  );

}


$(document).ready(function () {

    // Program Items
    var compareItem = 0;
    var compareItemLimit = 3;
    var currentItemID = '';
    var currentProgramItem = '';
    var currentGroupItem = '';

    // Stats & Ratios Items
    var compareStatItem = 0;
    var compareStatItemLimit = 4;
    var compareStatColumns = 2;
    var currentStatItemID = '';
    var currentStatItem = '';
    var currentStatGroupItem = '';

    // Array of column number to be filled with comparison data
    var columnArray4Stat = [[3, 8], [4, 9], [5, 10], [6, 11]];
    var statisticObj = new Array();

    var dataurl = SITE_URL + 'desktopmodules/iasggroups/Services/Programlist.aspx'; //'ajax/programs/getprogramList';
    var statDataURL = SITE_URL + 'desktopmodules/iasggroups/Services/getprogramstats.aspx'; //'ajax/programs/getProgramStatistic';
    var correlateDataURL = SITE_URL + 'desktopmodules/iasggroups/Services/getCorrelation.aspx';

    //Add S&P Index
    currentStatItemID = 973;
    currentStatItem = 'S&P 500 Index';
    currentStatGroupItem = 'United States Index';
    showHideStatRatio(0);
    addProgram2StatRatioComaparison();
    $("#statRatioACinput").val('Enter a program');
    function isNull(val) {

        return val == null
    }

    function limitChars(name, limit) {

        if (name != null || name == '') {
            if (name.length > limit) name = name.slice(0, limit).trim() + '...';
        }

        return name;
    }

    function format(item) {

        return '<p>' + item.group + '<br><span>' + item.program + '</span></p>';
    }

    function removeCompProgram() {
        compareItem--;
        chartID--;
    }

    function removeCompStatRatio() {

        removeCorrelationRow(compareStatItem);
        compareStatItem--;
    }

    function isProgramOverLimit(item, limit) {

        var result = false;

        if (item >= limit) {
            result = true;
            alert("Only " + limit + " items can be compared.");
        }

        return result;
    }

    function isProgramSelected(itemID) {
        var result = false;
        var element = $("#" + itemID)[0];

        if (element) {
            result = true;
            alert('This program has already been added to comparison list');
        }
        return result;
    }

    function getComparison(dataURL) {

        dataURL = dataURL + '&c=' + reqId;  //+ chartID;

        new google.visualization.Query(dataURL + '&t=CR', 'xhr').
    send(function (response) {
        if (response.isError()) {
            chartID++;
            reqId++;
            alert("The program you've just selected has no data for comparison");
            $("#removeCompProgram" + currentItemID).trigger('click');

            return;
        } else {

            data = response.getDataTable();
            programChartData[chartID] = data.clone();

            chartType = $("#id_chartType").val();
            switch (chartType) {
                case 'AUM':
                    {
                        $("#" + div_container).load(dataURL + '&t=AUM');
                        break;
                    }
                case 'CR':
                    {
                        drawChart(chartID);
                        break;
                    }

                default:
                    // fieldValue = parseFloat(fieldValue).formatNumber(2, '%');
            }


            reqId++;
            chartID++;

        }
    });
    }

    function programComparisonCheck() {

        var compareItem = '';

        $("input[type=checkbox][class=compareCheckBox]").each(function () {
            if ($(this).attr("checked")) {
                //
                //compareItem += '/' + $(this).attr("id") + '|' + encodeURIComponent($(this).attr("name")).replace('%2F', '%20').replace('%25', '').replace('%27', '');
                //Todo:
                compareItem += $(this).attr("id") + '|'
            }
        });

        if (compareItem == '') {


            chartType = $("#id_chartType").val();
            switch (chartType) {
                case 'AUM':
                    {
                        $("#" + div_container).load(dataCompSourceURL + initProgram + '&t=AUM');
                        break;
                    }
                case 'CR':
                    {
                        drawChart(0);
                        break;
                    }

                default:
                    // fieldValue = parseFloat(fieldValue).formatNumber(2, '%');
            }



        }
        else {
            //alert('Compare Item:' + compareItem);
            dataURL = dataCompSourceURL + initProgram + '|' + compareItem // + '&t=' + chartType;
            getComparison(dataURL);
        }

    }
    /******** Stat Ratio Tabs ***********/
    // (basic) click event handler for tab navigation
    $(".tabnav li a").click(function () {
        // de-activate tabs
        $(this).parent().parent().find("li").removeClass("active");

        // activate current tab
        $(this).parent().addClass("active");

        return false;
    });

    $("#stattabs li a").each(function () {
        $(this).click(function () {
            showHideStatRatio($(this).attr("href").replace('#', ''));

            return false;
        });
    });

    $("#sectionnav li a").each(function () {
        $(this).click(function () {
            sectionnav($(this).attr("href"))
            return false;
        });
    });

    function sectionnav(section) {
        $("#sectionnav li a").each(function () {
            $($(this).attr("href")).hide()
            //$($(this).attr("href")).hide()
        });
        $(section).show();
    }

    function showHideStatRatio(section) {

        for (x = 0; x < compareStatItemLimit; x++) {

            for (i = 0; i < compareStatColumns; i++) {

                if (i == section) {
                    $('#statRatioTable td:nth-child(' + columnArray4Stat[parseInt(x)][i] + '),#statRatioTable th:nth-child(' + columnArray4Stat[parseInt(x)][i] + ')').show();
                }
                else {
                    $('#statRatioTable td:nth-child(' + columnArray4Stat[parseInt(x)][i] + '),#statRatioTable th:nth-child(' + columnArray4Stat[parseInt(x)][i] + ')').hide();
                }

            }
        }

        if (section == 0) {
            $('#statRatioTable td:nth-child(' + (columnArray4Stat[parseInt(0)][0] - 1) + '),#statRatioTable th:nth-child(' + (columnArray4Stat[parseInt(0)][0] - 1) + ')').show();
            $('#statRatioTable td:nth-child(' + (columnArray4Stat[parseInt(0)][1] - 1) + '),#statRatioTable th:nth-child(' + (columnArray4Stat[parseInt(0)][1] - 1) + ')').hide();
        }
        else {
            $('#statRatioTable td:nth-child(' + (columnArray4Stat[parseInt(0)][0] - 1) + '),#statRatioTable th:nth-child(' + (columnArray4Stat[parseInt(0)][0] - 1) + ')').hide();
            $('#statRatioTable td:nth-child(' + (columnArray4Stat[parseInt(0)][1] - 1) + '),#statRatioTable th:nth-child(' + (columnArray4Stat[parseInt(0)][1] - 1) + ')').show();
        }

    }


    function removeStatRatio(colIndex) {

        deactivateRemove();

        for (x = colIndex; x < compareStatItemLimit; x++) {
            for (i = 0; i < compareStatColumns; i++) {

                $("#statRatioTable" + " th:first:nth-child("
          + columnArray4Stat[x][i] + ")").each(function () {

              if ((parseInt(x) + 1) >= parseInt(compareStatItemLimit)) {

                  $(this).html('');
              }
              else {
                  var headerObj = $("#statRatioTable" + " th:first:nth-child("
                  + columnArray4Stat[parseInt(x) + 1][i] + ")");
                  $(this).html(headerObj.html().replace('rel="' + (parseInt(x) + 1) + '"', 'rel="' + (parseInt(x)) + '"'));
                  //$(this).html(parseInt(x) );
                  headerObj.html('');
              }

              //              }

          });

                $("#statRatioTable" + " tr")
            .children("td:nth-child(" + columnArray4Stat[x][i] + ")")
                .each(function () {
                    //          if (x == compareStatItem) $(this).html('');
                    //          else {
                    if ((parseInt(x) + 1) >= parseInt(compareStatItemLimit)) {
                        $(this).html('');
                    }
                    else {
                        var columnObj = $(this).parents("tr").children("td:eq("
                          + columnArray4Stat[x][i] + ")");
                        $(this).html(columnObj.html());
                        //columnObj.html('');
                    }
                    //          }
                });
            }
        }
        for (i = parseInt(colIndex) + 1; i <= compareStatItem; i++) {
            $("#" + i).attr("id", (i - 1));
        }

        activateRemove();
        if (compareStatItem > 0) getCorrelation();

    }

    function removeCorrelationRow(row) {

        for (var i = 0; i < row; i++) {
            $("tr#corrolateRowID" + i).remove();
        }
    }

    function getStatRatio(itemID, colIndex) {
        $.ajax({
            type: "POST",
            url: statDataURL,
            data: "program_id=" + itemID,
            datatype: "json",
            success: function (result) {
                statisticObj[colIndex] = eval('(' + result + ')');
                if (!isNull(statisticObj[colIndex])) {

                    displayStatRatio(colIndex);
                }
                else {
                    alert("The program you've just selected has no data for comparison");
                    $('"img[class=removeCompStatProgram][id=' + (compareStatItem - 1) + ']"').trigger('click');
                }
            }
        });
    }

    function displayStatRatio(colIndex) {

        // Init regular expression to test number with decimal
        var pattern = new RegExp('^[-+]?[0-9]*\.[0-9]+$');
        var period = new Array('monthly', 'yearly');

        deactivateRemove();

        for (i = 0; i < compareStatColumns; i++) {
            // Set compared program title
            $("#statRatioTable" + " th:first:nth-child("
        + columnArray4Stat[colIndex][i] + ")").each(function () {
            //$(this).html(limitChars(currentStatItem, 9));
            $(this).html('<div><img rel="' + (compareStatItem - 1) + '" name="statRatioRemove" class="removeCompStatProgram" src="' + IMAGE_URL + 'remove.gif"/>' + limitChars(currentStatGroupItem, 17) + ' : ' + limitChars(currentStatItem, 18) + '</div>');

            $(this).css({ 'color': '#666' });
        });

            // Fill compared program data in each row that is matched <td id="array_key">
            $("#statRatioTable" + " tr")
        .children("td:nth-child(" + columnArray4Stat[colIndex][i] + ")")
        .each(function () {
            var fieldID = $(this).attr('id');
            var fieldValue = '';

            if (!isNull(statisticObj[colIndex][period[i]][fieldID]))
                fieldValue = statisticObj[colIndex][period[i]][fieldID];

            // Format the number for dislay
            if (pattern.test(fieldValue) == true) {
                switch (fieldID) {
                    case 'sharpe':
                    case 'kurtosis':
                    case 'calmar':
                        //fieldValue = parseFloat(fieldValue).formatNumber(2, '');
                        break;
                    case 'correlation_sp500':
                        //fieldValue = parseFloat(fieldValue).formatNumber(2, '');
                        break;
                    default:
                        // fieldValue = parseFloat(fieldValue).formatNumber(2, '%');
                }
            }

            if (fieldID != '' || fieldID != null) {
                $(this).html(fieldValue);
                //if (fieldID == 'max_dd') $(this).css({ 'color': '#FF4040' });
                //else 
                $(this).css({ 'color': '#666' });
            }
        });
        }
        activateRemove();
        getCorrelation();

    }


    function activateRemove() {
        $('[name$="statRatioRemove"]').click(function () {

            $("#" + $(this).attr('rel')).trigger('click')
        });

    }
    function deactivateRemove() {
        $('[name$="statRatioRemove"]').unbind('click');

    }

    function getCorrelation() {


        //var correlateProgramIDs = '/' + (refProgram).split("|", 1);
        var correlateProgramIDs = '?program_id=' + (refProgram).split("|", 1);
        var correlateItems = 0;
        var correlateProgramNames = new Array();
        var correlateProgramValues = new Array();

        //Remove Correlation row
        if (compareStatItem > 0) removeCorrelationRow(compareStatItem);

        //Collect All the Correlated Items
        $("li>div.statratioCompItem").each(function () {
            //correlateProgramIDs += '/' + $(this).attr("title");
            correlateProgramIDs += ',' + $(this).attr("title");
            correlateProgramNames.push($(this).html());
            correlateItems++;
        });

        //Get Correlated Data
        $.ajax({
            url: correlateDataURL + correlateProgramIDs,
            datatype: "json",
            success: function (result) {

                //Mapping return data
                correlateProgramValues = eval('(' + result + ')'); //alert(correlateProgramValues);

                for (var i = 0; i < correlateItems; i++) {

                    //Adding row to the end of the table (before dummy row)
                    $('#statRatioTable tbody>tr:last').clone()
           .insertBefore('#statRatioTable tbody>tr:last').filter(function () {

               //Check if the previous row has alternate css assigned 
               if ($(this).prev().attr("class") == "oddrow") $(this).attr({ "class": "" });
               else $(this).attr({ "class": "oddrow" });

               //Assign ID to added <tr>
               $(this).attr({ "id": "corrolateRowID" + i });

               //Loop through <td> within <tr>(parent)
               $(this).children().each(function () {
                   if ($(this).attr('id') == 'programTitle') $(this).html(correlateProgramNames[i]);
                   else {

                       var fieldID = $(this).attr('id');
                       var fieldValue = '';
                       var matrixIndex = 'program' + (i + 1);

                       parseFloat(fieldValue).formatNumber(3, '');

                       if (!isNull(correlateProgramValues[matrixIndex][fieldID]))
                           fieldValue = parseFloat(correlateProgramValues[matrixIndex][fieldID])
                                         .formatNumber(2, '');

                       if (fieldID != '' || fieldID != null) $(this).html(fieldValue);
                   }

               }); // end looping <td>

           }); //end adding row

                } //end for()
            } //end success
        }); //end ajax call

    }


    function addProgram2StatRatioComaparison() {

        if (isProgramOverLimit(compareStatItem, compareStatItemLimit) == false &&
    isProgramSelected('statratio' + currentStatItemID) == false) {

            var objStatRatio = $("#selectedStatRatio").append('<li class="aclist-data">' +
            '<input id="statratio' +
      currentStatItemID +
      '" style="display:none;" name="' +
      currentStatItem +
      '" type="checkbox" value="' +
      currentStatItemID +
      '" checked="checked" />' +
      '<div class="statratioCompItem" title="' +
      currentStatItemID +
      '">' +
      limitChars(currentStatGroupItem, 17) +
      ' : ' +
      limitChars(currentStatItem, 18) +
      '</div><img id="' +
            //currentStatItemID +
            (compareStatItem) +
      '" class="removeCompStatProgram" src="' +
      IMAGE_URL +
      'remove.gif"/></li>');
            getStatRatio(currentStatItemID, compareStatItem);
            //$('#' + (compareStatItem), objStatRatio[0]).click(function () {
            $('#' + (compareStatItem)).click(function () {
                $(this).unbind('click', removeCompStatRatio()).parent().remove();
                removeStatRatio($(this).attr('id'));
            });


            compareStatItem++;

            $("#statRatioACinput").val('');

        }
        else {
            $("#statRatioACinput").val('');
            return false;
        }

    };

    function addProgram2ChartComaparison() {
        if (isProgramOverLimit(compareItem, compareItemLimit) == false &&
    isProgramSelected(currentItemID) == false) {

            var objProgram = $("#selectedProgram").append('<li class="aclist-data"><input id="' +
      currentItemID +
      '" class="compareCheckBox" name="' +
      currentProgramItem +
      '" type="checkbox" value="' +
      currentItemID +
      '" checked="checked" /><div> ' +
      limitChars(currentGroupItem, 17) +
      ' : ' +
      limitChars(currentProgramItem, 18) +
      '</div><img id="removeCompProgram' +
      currentItemID +
      '" class="removeCompProgram" src="' +
      IMAGE_URL +
      'remove.gif"/></li>');

            compareItem++;
            $('.removeCompProgram', objProgram[0]).unbind();
            $('.removeCompProgram', objProgram[0]).click(function () {
                $(this).unbind('click', removeCompProgram()).parent().remove();
                programComparisonCheck();
            });

            $("#programACinput").val('');

            $("input[type=checkbox][id=" + currentItemID + "]").bind("change", function (event) {
                programComparisonCheck();
            });

            programComparisonCheck();

        }
        else {
            $("#programACinput").val('');
            return false;
        }

    }


    $("#programACinput, #statRatioACinput").autocomplete(dataurl, {
        multiple: false,
        parse: function (data) {
            return $.map(eval(data), function (row) {
                return {
                    data: row,
                    value: row.group,
                    result: limitChars(row.group, 25).asciiDecode() + ' : '
                        + limitChars(row.program, 30).asciiDecode()
                }
            });
        },
        formatItem: function (item) {
            return format(item);
        }
    }).result(function (e, item) {

        var object_id = $(this).attr('id');

        switch (object_id) {

            case 'programACinput':
                currentItemID = item.id;
                currentProgramItem = (item.program).asciiRemove();
                currentGroupItem = (item.group).asciiRemove();
                addProgram2ChartComaparison();
                break;

            case 'statRatioACinput':
                currentStatItemID = item.id;
                currentStatItem = (item.program).asciiRemove();
                currentStatGroupItem = (item.group).asciiRemove();
                addProgram2StatRatioComaparison();
                break;
        }

    });

    $("#programACinput, #statRatioACinput").focus(function () {
        if ($(this).val() == 'Enter a program') {
            $(this).val('');
            $(this).removeClass('midgrey');
        }
    });

    $("#programACinput, #statRatioACinput").blur(function () {
        if ($(this).val() == '') {
            $(this).val('Enter a program');
            $(this).addClass('midgrey');
        }
    });


    $("#showProgramStrategySummary").attr("disabled", "disabled");


    $("#showProgramDueDiligence").click(function () {
        $("#showSummary").hide();
        $("#dueDiligence").show();
        $("#showProgramStrategySummary").removeAttr('disabled');
        $("#showProgramDueDiligence").attr("disabled", "disabled");
    });


    $("#showProgramStrategySummary").click(function () {
        $("#dueDiligence").hide();
        $("#showSummary").show();
        $("#showProgramDueDiligence").removeAttr('disabled');
        $("#showProgramStrategySummary").attr("disabled", "disabled");
    });
    $("#id_addindex").change(function () {
        if ($(this).val() != '0') {
            currentItemID = $(this).val();
            currentProgramItem = ''; 
            currentGroupItem = $("#id_addindex option:selected").text();
            addProgram2ChartComaparison();
        }
    });
    $("#id_addindexstatRatio").change(function () {
        if ($(this).val() != '0') {
            currentStatItemID = $(this).val();
            currentStatItem = '';
            currentStatGroupItem = $("#id_addindexstatRatio option:selected").text();
            addProgram2StatRatioComaparison();
        }
    });

});

function changeType(type) {

    switch (type) {
        case 'AUM':
            {
                $("#id_compare").css("display", "none");
                $(".aclist-data").css("display", "none");
                $("#chartname").text("Assets Managed & Cumulative Returns");
                $("#" + div_container).load(dataCompSourceURL + initProgram + '&t=AUM');

                //                    var compareItem = '';

                //                    $("input[type=checkbox][class=compareCheckBox]").each(function() {
                //                        if ($(this).attr("checked")) {

                //                            compareItem += $(this).attr("id") + '|'
                //                        }
                //                    });

                //                    if (compareItem == '') {

                //                      $("#" + div_container).load(dataCompSourceURL + initProgram + '&t=AUM');
                //                    }
                //                    else {
                //                        dataURL = dataCompSourceURL + initProgram + '|' + compareItem // + '&t=' + chartType;
                //                        $("#" + div_container).load(dataURL + '&t=AUM');
                //                    }

                break


            }
        case 'CR':
            {

                $("#chartname").text("Cumulative Returns");
                //$("chartname").show;
                chartType = type;
                $("#" + div_container).html("");
                chart = new google.visualization.AnnotatedTimeLine(document.getElementById(div_container));
                drawChart(chartID - 1);
                $("#id_compare").css("display", "inherit");
                $(".aclist-data").css("display", "inherit");

                break
            }
        case 'Rolling':
            {
                $("#id_compare").css("display", "none");
                //$("selected_panel").css("display", "none");
                $(".aclist-data").css("display", "none");

                $("#chartname").text("Monthly ROR / Rolling Averages");
                chartType = type;
                $("#" + div_container).html("");
                pfmDataURL = dataInitSourceURL + initProgram + '&c=' + reqId + '&t=' + chartType; //+'/'+chartID;
                chart = new google.visualization.AnnotatedTimeLine(document.getElementById(div_container));

                new google.visualization.Query(pfmDataURL, 'xhr').send(function (response) {
                    if (response.isError()) {
                        //Display error message
                        if ($("#" + div_container).length) {
                            $("#" + div_container).css({ 'background': 'none', 'margin-top': '15px', 'padding': '15px 0', 'height': '15px', 'color': 'red' });
                            $("#" + div_container).html(response.getMessage());
                        }
                        // Disable Auto complete Comparision, but need to check if the oject exists
                        if ($("#programStatsRatioAutoCompDIV").length) $("#programStatsRatioAutoCompDIV").hide();
                        if ($("#programChartAutoCompDIV").length) $("#programChartAutoCompDIV").hide();
                        return;
                    } else {
                        //data = response.getDataTable();
                        //programChartData[chartID] = data.clone();
                        //drawChart(chartID);
                        var alphaValue = 0;

                        chart.draw(response.getDataTable(), { displayAnnotations: true, displayRangeSelector: false, scaleType: 'maximize', fill: alphaValue, wmode: 'transparent', displayZoomButtons: false });

                        //chartID++;
                        reqId++;
                    }
                });

                break
            }
        case 'Distribution':
            {
                $("#id_compare").css("display", "none");
                $(".aclist-data").css("display", "none");
                $("#chartname").text("Distribution of Monthly Returns");
                //$("chartname").hide;
                chartType = type;
                $("#" + div_container).html("");
                pfmDataURL = dataInitSourceURL + initProgram + '&c=' + reqId + '&t=' + chartType; //+'/'+chartID;
                chart = new google.visualization.ColumnChart(document.getElementById(div_container));

                new google.visualization.Query(pfmDataURL, 'xhr').send(function (response) {
                    if (response.isError()) {
                        //Display error message
                        if ($("#" + div_container).length) {
                            $("#" + div_container).css({ 'background': 'none', 'margin-top': '15px', 'padding': '15px 0', 'height': '15px', 'color': 'red' });
                            $("#" + div_container).html(response.getMessage());
                        }
                        // Disable Auto complete Comparision, but need to check if the oject exists
                        if ($("#programStatsRatioAutoCompDIV").length) $("#programStatsRatioAutoCompDIV").hide();
                        if ($("#programChartAutoCompDIV").length) $("#programChartAutoCompDIV").hide();
                        return;
                    } else {
                        //data = response.getDataTable();
                        //programChartData[chartID] = data.clone();
                        //drawChart(chartID);
                        var alphaValue = 0;
                        chart.draw(response.getDataTable(), { displayAnnotations: true, displayRangeSelector: false, scaleType: 'maximize', fill: alphaValue, wmode: 'transparent', legend: 'none' });
                        //chartID++;
                        reqId++;
                    }
                });

                break
            }


        default: { break }
    }


}
