/* portfolioSummary component, write logic of portfolioSummary module in this class */
var objs=new Array();
var heightOfSvg=0;
var heightOfChartDiv=0;
var heightOfChartDiv2=0;
var portfolioSummary = $.extend( new Component("portfolioSummary"), {
    bykey: "", ccy: "",currentAllocationType: "",amcharts: {},data: {}//cache data
});

app.registerComponent(portfolioSummary);

portfolioSummary.changePieAndBarFlag = {"pie":false,"bar":false};
portfolioSummary.changePieAndBar2Flag = {"pie":false,"bar":false};

portfolioSummary.amcharts.pickColor = function(type, obj, byccy){
    var assetColor = {"Bonds": "#9C9E9C", "Funds": "#EFBEBD", "Equities": "#636163",
                            "Cash": "#E7D38C", "Structured Products": "#7BAAAD",
                            "Money Accounts": "#DE1839", "Others": "#CE8E00"};
    var currencyColor = {HKD: "#A59EA5", EUR: "#EFBEB5", AUD: "#5A5D5A", JPY: "#E7D38C",
                          USD: "#84AAAD", SGD: "#CE2421", OTHER:"#CE8E00"};
    var returnColor = "";
    if(byccy){
        if(currencyColor[byccy]){
            returnColor = currencyColor[byccy];
        };
    }else if(type == "currency"){
        if(currencyColor[obj[type]]){
            returnColor = currencyColor[obj[type]];
        }
    }else if(type == "asset"){
        if(assetColor[obj[type]]){
            returnColor = assetColor[obj[type]];
        }
    }
    if(!returnColor || returnColor == ""){
        returnColor = this.backupColor.pop();
    }
    return returnColor;
};

portfolioSummary.init = function (chartData, akey, avalue, chartType, divId) {
    var self = this;
    var legend, chart = null;
    if(!chartData || chartData.length <= 0 ){
        $("#" + divId).empty();
        return ;
    }
    this.amcharts.backupColor = ["#C72C95","#D8E0BD","#B3DBD4","#69A55C",
         "#B5B8D3","#F4E23B","#A4E11B","#FF6600","#FCD202","#B0DE09","#0D8ECF",
         "#2A0CD0","#CD0D74","CC0000#","#00CC00","#0000CC","#DDDDDD"];
    if(chartType == "PIE"){
        this.currentAllocationType = avalue;
        // PIE CHART
        chart = new AmCharts.AmPieChart();
       /* $.each(chartData, function(i, e){
            e.color = self.amcharts.pickColor(akey,e);
        });*/
        chart.startAngle=45;
        chart.pullOutRadius = 0;
        chart.startDuration = 0;
        chart.dataProvider = chartData;
        chart.dataProvider.sort(this.compare);
        //chart.colorField = "color"; 
        chart.colors = ["#DE1839","#7BAAAD","#636163","#EFBEBD","#9C9E9C","#CE8E00","#E7D38C"];
        chart.titleField = akey;
        chart.valueField = avalue;
        chart.outlineColor = "#FFFFFF";
        chart.outlineAlpha = 0;
        chart.outlineThickness = 0;
        chart.radius = 90;
        chart.style = "";
        chart.numberFormatter = {precision: 0, decimalSeparator: '.', thousandsSeparator: ','};
        chart.labelRadius = 18;
        chart.labelText = "[[title]]\n([[percents]]%)";
        chart.marginBottom = 0;
        chart.pieX = "50%";
        chart.pieY = 250;
        if(chartData && chartData.length <= 1){
            chart.pullOutRadius = "0%";
        }
        // LEGEND
        legend = new AmCharts.AmLegend();
        legend.switchable = false;
        legend.align = "center";
        legend.markerType = "square";
        legend.maxColumns = 1;
        legend.valueWidth = 140;
        legend.style = "";
        chart.addLegend(legend);
    }else if(chartType == "BAR"){
        // SERIAL CHART
        chart = new AmCharts.AmSerialChart();
        $.each(chartData, function(i, e){
            e.color = self.amcharts.pickColor(akey,e);
        });
        chart.dataProvider = chartData;
        chart.categoryField = akey;
        chart.numberFormatter = {precision:0, decimalSeparator:'.', thousandsSeparator:','};           
        chart.rotate = false;

        // AXES
        // Category
        var categoryAxis = chart.categoryAxis;
        categoryAxis.autoGridCount = false;
        categoryAxis.gridPosition = "start";
        categoryAxis.axisColor = "#DADADA";
        categoryAxis.fillAlpha = 1;
        categoryAxis.gridAlpha = 0;
        categoryAxis.fillColor = "#FAFAFA";
        //categoryAxis.labelRotation = 90;

        // value
        var valueAxis = new AmCharts.ValueAxis();
        valueAxis.axisColor = "#DADADA";
        valueAxis.title = "";
        valueAxis.gridAlpha = 0.1;
        chart.addValueAxis(valueAxis);

        // GRAPH
        var graph = new AmCharts.AmGraph();
        graph.title = "Value";
        graph.valueField = avalue;
        graph.type = "column";
        //graph.balloonText = "Value in [[category]]:[[value]]";
        graph.lineAlpha = 0;
        graph.fillAlphas = 1;
        graph.colorField = "color";
        
        chart.addGraph(graph);

    }else if (chartType == "BAR_STACKED"){
        // SERIALL CHART
        chart = new AmCharts.AmSerialChart();
        chart.dataProvider = chartData;
        chart.categoryField = "asset";
        chart.numberFormatter = {precision:0, decimalSeparator: '.', thousandsSeparator: ','};
        chart.rotate = false;
        chart.marginLeft = 10;
        chart.marginRight = 1;

        // AXES
        // Category
        var categoryAxis = chart.categoryAxis;
        categoryAxis.autoGridCount = false;
        categoryAxis.gridPosition = "start";
        categoryAxis.axisColor = "#DADADA";
        categoryAxis.fillAlpha = 1;
        categoryAxis.gridAlpha = 0;
        categoryAxis.fillColor = "#FAFAFA";
        //categoryAxis.labelRotation = 90;
        
        // value                      
        var valueAxis = new AmCharts.ValueAxis();
        valueAxis.stackType = "regular";
        valueAxis.gridAlpha = 0.1;
        valueAxis.axisAlpha = 0;
        chart.addValueAxis(valueAxis);
        
        var graphs = {};
        for (var i = 0; i < chartData.length; i++){
            $.each(chartData[i], function(key, value){
                if(key != "asset"){
                    graphs[key] = "";
                }else{
                    chartData[i].asset = chartData[i].asset.replaceAll(" ","\n");
                }
            });
        }
        var ccy = ["USD", "JPY", "HKD", "SGD", "EUR", "AUD", "OTHER"];
	    for(var idx in ccy){
	        $.each(graphs, function(key, value){
	        	if(key==ccy[idx]){
		            var graph = new AmCharts.AmGraph();
		            graph.title = key;
		            //graph.labelText = "[[value]]";
		            graph.valueField = key;
		            graph.type = "column";
		            graph.lineAlpha = 0;
		            graph.fillAlphas = 1;
		            graph.lineColor = portfolioSummary.amcharts.pickColor(null,null,key);
		            chart.addGraph(graph);
	        	}
	        });
        }
        
        // LEGEND
        var legend = new AmCharts.AmLegend();
        legend.switchable = false;
        legend.align = "center";
        legend.maxColumns = 3;
        legend.valueWidth = 40;
        legend.autoMargins = false;
        legend.marginLeft = 0;
        legend.marginRight = 0;
        legend.style = "";
        chart.addLegend(legend);
    }
    
    $("#" + divId).empty();
    chart.write(divId);// WRITE
    /*
    objs[divId]={chartData:chartData, akey:akey, avalue:avalue, chartType:chartType, divId:divId};
    window.onresize = function(){
    	for(var i in objs){
    		portfolioSummary.init(objs[i].chartData,objs[i].akey, objs[i].avalue, objs[i].chartType, objs[i].divId); 
    	}
    };*/
    heightOfSvg=$("svg[version='1.1']").height();
    heightOfChartDiv=$($("#chartdiv").find("div").get(0)).height();
    heightOfChartDiv2=$($("#chartdiv2").find("div").get(0)).height();
};

portfolioSummary.assetAllocationByAsset = function (){
    portfolioSummary.changePieAndBarFlag["pie"] = true;
    var self = this;
    var url = "portfolio/assetAllocationByAsset/" + this.bykey + "?asOfDate=" + app.selectDateValue;
    var returnBack = ajaxCall({ url: app.EPRESTAPI_CONTEXT_ROOT + url , dataType: "json"}, false);
    returnBack.done(function(data){
        var allocation = data.data.result.allocation ;
        var chartData = [];
        $.each(allocation, function(key, value){
            chartData.push({asset: key, assetValue: value});
        });

        self.init(chartData, "asset", "assetValue", "PIE", "chartdiv");
        portfolioSummary.changePieAndBarFlag["pie"] = false;
    });
};

portfolioSummary.detailAssetAllocationByAsset = function (){
    portfolioSummary.changePieAndBarFlag["bar"] = true;
    var self = this;
    var url = "portfolio/detailAssetAllocationByAsset/" + this.bykey + "?asOfDate=" + app.selectDateValue;
    var returnBack = ajaxCall({ url: app.EPRESTAPI_CONTEXT_ROOT + url , dataType: "json"}, false);
    returnBack.done(function(data){
        var allocation = data.data.result.allocation ;
        var chartData = [];
        
        $.each(allocation, function(key, value){
            var arr = key.split("_");
            var isIn = false;
            var data = {};
            for(var i = 0; i < chartData.length; i++){
                if(chartData[i]["asset"] == arr[0]){
                    isIn = true;
                    data = chartData[i];
                    break;
                }
            }
            if(isIn){
                var hasTheProperty = false;
                $.each(data, function(key2, value2){
                    if(arr[1] == key2){
                        data[arr[1]] = value2 + value;
                        hasTheProperty = true;
                    }
                });
                if(!hasTheProperty){
                    data[arr[1]] = value;
                }
                
            }else{
                data["asset"] = arr[0];
                data[arr[1]] = value;
                chartData.push(data);
            }
            
        });
        self.init(chartData, "asset", "assetValue", "BAR_STACKED", "chartdiv");
        portfolioSummary.changePieAndBarFlag["bar"] = false;
    });
};

portfolioSummary.assetAllocationByCurrency = function (){
    portfolioSummary.changePieAndBar2Flag["pie"] = true;
    var self = this;
    var url = "portfolio/assetAllocationByCurrency/" + portfolioSummary.bykey + "?asOfDate=" + app.selectDateValue;
    var returnBack = ajaxCall({ url: app.EPRESTAPI_CONTEXT_ROOT + url , dataType: "json"}, false);
    returnBack.done(function(data){
        var allocation = data.data.result.allocation ;
        var chartData = [];
        $.each(allocation, function(key, value){
            chartData.push({currency: key, currencyValue: value});
        });
        self.init(chartData, "currency", "currencyValue", "PIE", "chartdiv2");
        portfolioSummary.changePieAndBar2Flag["pie"] = false;
    });
};

portfolioSummary.detailAssetAllocationByCurrency = function (){
    portfolioSummary.changePieAndBar2Flag["bar"] = true;
    var self = this;
    var url = "portfolio/detailAssetAllocationByCurrency/" + this.bykey + "?asOfDate=" + app.selectDateValue;
    var returnBack = ajaxCall({ url: app.EPRESTAPI_CONTEXT_ROOT + url , dataType: "json"}, false);
    returnBack.done(function(data){
        var allocation = data.data.result.allocation ;
        var chartData = [];
        $.each(allocation, function(key, value){
            chartData.push({currency: key, currencyValue: value});
        });
        self.init(chartData, "currency", "currencyValue", "BAR", "chartdiv2");
        portfolioSummary.changePieAndBar2Flag["bar"] = false;
    });
};

portfolioSummary.renderDataCallBack = function (template, data) {
    if(data.summaryTable.colsCount < 9){
        $("#summaryPositionDTable tr").each(function(i,e){
            if(i == 0){
                $(e).append("<th></th>");
            }else{
                if(i >= $("#summaryPositionDTable tr").length-1){
                    $(e).append("<td class='pSummaryRowbg'></td>");
                }else{
                    $(e).append("<td></td>");
                }
                
            }
        });
    }
    if(portfolioSummary.ccy){
        var headTotal = "(" + portfolioSummary.ccy + ")";
        $("#headTotal").empty().append(headTotal);
    }
    
};

portfolioSummary.change = function (values, tableType) {
    var retArr = [];
    var commonNullItem = {value: "-", refValue: "-",percentage: "-"};
    var length = values.length - 1;
    if (tableType == "OtherCurrency"){
        length = values.length ;
    }
    for(var i = 1; i < length; i++){
        if(values[i] && values[i].percentage && (values[i].percentage + "").indexOf("%") == -1){
            values[i].percentage = values[i].percentage + "%";
        }
        if(values[i]){
            $.each(values[i], function(property, propertyValue){
                if(!propertyValue){
                    values[i][property] = "-";
                }
            });
        }else{
            values[i] = commonNullItem;
        }
        
        retArr.push(values[i]);
    }
    return retArr;
};

portfolioSummary.changeToPercent = function (value) {
    if(value && (value + "").indexOf("%") == -1){
        value = value + " %";
    }
    if(!value){
        return "-";
    }
    return value;
};

portfolioSummary.findItemByAssetClassType = function (assetClassType, totalCol) {
    for(var i = 0; i < totalCol.length; i++){
        if(totalCol[i].assetClassType == assetClassType){
            return totalCol[i];
        };
    };
    return null;
};

portfolioSummary.findItemByCurrency = function (currency, itemRow) {
    for(var i = 0; i < itemRow.length; i++){
        if(itemRow[i].currency == currency){
            return itemRow[i];
        };
    };
    return null;
};

portfolioSummary.drawTable = function (data, tableType){
    if(!data){
        data = this.data ; 
    }
    var items = null ;
    var summaryTable = {};
    
    summaryTable.titles = [];
    summaryTable.rows = [];
    summaryTable.creditRow = [];
    summaryTable.colsCount = 0;
    summaryTable.tableType = tableType;
    if (tableType == "OtherCurrency") {//Detail of Other Currency Tab
        items = data.data.result.otherItems ;
        for(var i = 0; i < items.length; i++){
            if(items[i] && items[i].currency){
                var isIn = $.inArray(items[i].currency,summaryTable.titles);
                if(isIn == -1){
                    summaryTable.titles.push(items[i].currency);
                }
            }
        }
        summaryTable.colsCount = summaryTable.titles.length + 1;
    }else {//default:AssetAllocation Tab
        items = data.data.result.items ;
        summaryTable.titles = ["USD", "JPY", "HKD", "SGD", "EUR", "AUD", "OTHER"];
        summaryTable.colsCount = summaryTable.titles.length + 2;
    }
    
    
    for(var i = 0; i < items.length; i++){
        if(items[i] && items[i].assetClassType){
            var rowIndex = "";
            var flag = false;
            for(var j = 0; j < summaryTable.rows.length; j++){
                var cells = summaryTable.rows[j];
                if(cells[0].assetClassType == items[i].assetClassType){
                    rowIndex = j;
                    flag = true;
                    break;
                };
            };

            if(flag){
                for(var k = 0; k < summaryTable.titles.length; k++){
                    if(items[i].currency === summaryTable.titles[k]){
                        summaryTable.rows[rowIndex][k + 1] = items[i];
                    }
                }; 
            }else{
                //new row and insert
                var cells = new Array(summaryTable.colsCount);
                cells[0] = items[i];
                for(var l = 0; l < summaryTable.titles.length; l++){
                    if(items[i].currency === summaryTable.titles[l]){
                        cells[l + 1] = items[i];
                    } 
                }; 
                if (tableType != "OtherCurrency") {
                    var itemTotalCol = this.findItemByAssetClassType(items[i].assetClassType, data.data.result.totalCol);
                    cells[summaryTable.titles.length + 1] = itemTotalCol;
                }
                summaryTable.rows.push(cells);
            };
            
        };//end if
     }//end for items
    
  //total row begin
    var cellsTotalRow = new Array(summaryTable.colsCount);
    var totalRows = null;
    if (tableType == "OtherCurrency") {
        totalRows = data.data.result.totalRowForOthers ;
    }else{
        totalRows = data.data.result.totalRow ;
    }
    
    for(var i = 0; i < summaryTable.titles.length; i++){
        var itemTotalRow = this.findItemByCurrency(summaryTable.titles[i], totalRows);
        cellsTotalRow[ i + 1 ] = itemTotalRow;
    }
    var itemTemp = {};
    itemTemp.assetClassType = "Total";
    cellsTotalRow[0] = itemTemp;
    if (tableType != "OtherCurrency") {
        var itemTemp2 = {};
        itemTemp2.refValue = "";
        itemTemp2.percentage = "";
        cellsTotalRow[summaryTable.titles.length + 1] = data.data.result.totalInRefValue ;
    }
    summaryTable.rows.push(cellsTotalRow);
  //total row end
    
  //credit row begin  
    if (tableType != "OtherCurrency") {
        var cellsCredit = new Array(summaryTable.titles.length + 2);
        for(var i = 0; i < summaryTable.titles.length; i++){
            var itemCreditRow = this.findItemByCurrency(summaryTable.titles[i], data.data.result.creditItems);
            cellsCredit[ i + 1 ] = itemCreditRow;
        }
        var itemTemp2 = {};
        itemTemp2.assetClassType = "Credit";
        cellsCredit[0] = itemTemp2;
        cellsCredit[summaryTable.titles.length + 1] = data.data.result.creditTotal;
        summaryTable.creditRow.push(cellsCredit);
    }else{
        var cellsCredit = new Array(summaryTable.titles.length + 1);
        for(var i = 0; i < summaryTable.titles.length; i++){
            var itemCreditRow = this.findItemByCurrency(summaryTable.titles[i], data.data.result.creditItems);
            cellsCredit[ i + 1 ] = itemCreditRow;
        }
        var itemTemp2 = {};
        itemTemp2.assetClassType = "Credit";
        cellsCredit[0] = itemTemp2;
        summaryTable.creditRow.push(cellsCredit);
    }
  //credit row end
    
    var data = {};
    data.summaryTable = summaryTable;
    
    this.render("template/portfolio_summary_table.html", "summaryTableZone", data).done(this.renderDataCallBack);
    
    var headTotal = "";
    if(this.ccy){
        headTotal = headTotal + "(" + this.ccy + ")";
        $("#headTotal").empty().append(headTotal);
    }
    
    
    
    var otherItems = this.data.data.result.otherItems;
    if(otherItems && otherItems.length > 0){
        $("#otherCurrencyButton").css("display","inline");
    }
};

//order:desc
portfolioSummary.compare = function (obj1, obj2){
    if(obj1 && obj2 && obj1[portfolioSummary.currentAllocationType]){
        if(obj1[portfolioSummary.currentAllocationType] > obj2[portfolioSummary.currentAllocationType]){
            return -1;
        }else if(obj1[portfolioSummary.currentAllocationType] < obj2[portfolioSummary.currentAllocationType]){
            return 1;
        }
    }
    return 0;
};


portfolioSummary.pieChatButtonClick = function (button){    
    if($(button).hasClass("greyDivButton")){
        if (portfolioSummary.changePieAndBarFlag["bar"]){
            return ;
        }
        this.showLoading("chartdiv");       
        this.assetAllocationByAsset();
        $(button).removeClass("greyDivButton");
        $(button).addClass("redDivButton");
        $("#barChatButton").removeClass("redDivButton");
        $("#barChatButton").addClass("greyDivButton");
        trackAction("PortfolioSummary - SwitchToPieChartByAsset");
    }
};

portfolioSummary.barChatButtonSearchClick = function (button){    
    if($(button).hasClass("greyDivButton")){
        if (portfolioSummary.changePieAndBarFlag["pie"]){
            return ;
        }
        this.showLoading("chartdiv");
        $(button).removeClass("greyDivButton");
        $(button).addClass("redDivButton");
        $("#pieChatButton").removeClass("redDivButton");
        $("#pieChatButton").addClass("greyDivButton");
        this.detailAssetAllocationByAsset();
        trackAction("PortfolioSummary - SwitchToBarChartByAsset");
    }
};

portfolioSummary.pieChatButton2Click = function (button){
    if($(button).hasClass("greyDivButton")){
        if (portfolioSummary.changePieAndBar2Flag["bar"]){
            return ;
        }
        this.showLoading("chartdiv2");
        this.assetAllocationByCurrency();
        $(button).removeClass("greyDivButton");
        $(button).addClass("redDivButton");
        $("#barChatButton2").removeClass("redDivButton");
        $("#barChatButton2").addClass("greyDivButton");
        trackAction("PortfolioSummary - SwitchToPieChartByCurrency");
    }
};

portfolioSummary.barChatButton2SearchClick = function (button){
    if($(button).hasClass("greyDivButton")){
        if (portfolioSummary.changePieAndBar2Flag["pie"]){
            return ;
        }
        this.showLoading("chartdiv2");
        this.detailAssetAllocationByCurrency();
        $(button).removeClass("greyDivButton");
        $(button).addClass("redDivButton");
        $("#pieChatButton2").removeClass("redDivButton");
        $("#pieChatButton2").addClass("greyDivButton");
        trackAction("PortfolioSummary - SwitchToBarChartByCurrency");
    }
};

portfolioSummary.assetAllocationButtonClick = function (button){
    var otherItems = this.data.data.result.otherItems;
    if(!otherItems || otherItems.length == 0){
        return;
    }
    if($(button).hasClass("greyDivButton2")){
        this.drawTable();
        $(button).removeClass("greyDivButton2");
        $(button).addClass("blackDivButton2");
        $("#otherCurrencyButton").removeClass("blackDivButton2");
        $("#otherCurrencyButton").addClass("greyDivButton2");
        trackAction("PortfolioSummary - SwitchToAssetAllocationTable");
    }
};

portfolioSummary.otherCurrencyButton = function (button){
    var otherItems = this.data.data.result.otherItems;
    if(!otherItems || otherItems.length == 0){
        return;
    }
    if($(button).hasClass("greyDivButton2")){
        this.drawTable(null, "OtherCurrency");
        $(button).removeClass("greyDivButton2");
        $(button).addClass("blackDivButton2");
        $("#assetAllocationButton").removeClass("blackDivButton2");
        $("#assetAllocationButton").addClass("greyDivButton2");
        trackAction("PortfolioSummary - SwitchToOtherCurrenciesTable");
    }
};

//main function
portfolioSummary.on( "load", function(bpkey, displayDivId){
    trackAction("PortfolioSummary - View");
    var self = this;
    if(bpkey) {
        this.bykey = bpkey;
    }else if($.isArray(app.user.bpKey)) {
        this.bykey = app.selectBpKey;
    }else {
        this.bykey = app.user.bpKey;
    }
    if(!this.bykey){
        return; 
    }
    
    if(!displayDivId){//sumarryMainContent
        displayDivId = "mainContent";
    }
    displayDivId=app.mainComponentDivId;
    $("#" + displayDivId).empty();
    var data = {bpkey: this.bykey};
    return this.render("template/portfolio_summary.html", displayDivId, data).done(function(){
        self.showLoading("chartdiv");
        self.showLoading("chartdiv2");
        self.showLoading("summaryTableZone");
        
        $("#summarySelectAsofdate").val(app.selectDateValue);
        $("#summarySelectAsofdate").die().live("change",function(){
            trackAction("PortfolioSummary - ChangeDate");
            app.trigger("changeAsOfDate", null, $("#summarySelectAsofdate").val()).done(function(){
            	self.trigger("load", null, displayDivId);
            });
        });

        //draw first chart
        self.assetAllocationByAsset();
        //draw second chart
        self.assetAllocationByCurrency();
        
        $("#accountNumber").empty().append(self.bykey);
        getNetAssetValue(self.bykey).done(function(data){
            var liabilitiesValue = data.data.result.liabilitiesValue;
            var grossAssetValue = data.data.result.grossAssetValue;
            var netAssetValue = data.data.result.netAssetValue;
            var currency = data.data.result.refccy;
            if(!currency){
                currency = "";
            }
            self.ccy = currency;
            $("#netAssetValue").empty().append(currency + " " + netAssetValue);
            $("#grossAssetValue").empty().append(currency + " " + grossAssetValue);
            $("#liabilitiesValue").empty().append(currency + " " + liabilitiesValue);
            var headTotal = "";
            if(self.ccy){
                headTotal = headTotal + "(" + self.ccy + ")";
                $("#headTotal").empty().append(headTotal);
            }
        });
        
        //summary table 
        var url = "portfolio/summary/" + self.bykey + "?asOfDate=" + app.selectDateValue;
        var returnBack = ajaxCall({ url: app.EPRESTAPI_CONTEXT_ROOT + url, dataType: "json"}, false);
        returnBack.done(function(data){
            self.data = data;
            self.drawTable(data, "AssetAllocation");
        });

        
        $(window).resize(function(){
        	$("svg[version='1.1']").css({ "max-height" :heightOfSvg+"px", "height" : heightOfSvg+"px" });
    		$($("#chartdiv").find("div").get(0)).css({"width" : "433px","height" : heightOfChartDiv+"px"});
    		$($("#chartdiv2").find("div").get(0)).css({"width" : "433px","height" : heightOfChartDiv2+"px"});
    		
        });
        
    });    
});