$(function() {
    'use strict';
    var cl = BWA.ChartLayout = function(options) {
        options = options || {};
        if (!options.divs) {
            throw new Error('needs ids in ChartLayout.');
        }

        this.initialized = false;
        this.divs = options.divs;
        //hcLee 2015 07 20 V14.1-V15.1  배열이 필요, 만일 2개 이상의 화면을 가진 멀티뷰어이면 이배열 확장 필요함.
        //현재 IBEMS의 경우 2개 이상인 경우 없음.
        this.fullscreenElement = [{
            divInfo: null,
            width: null,
            chartSize: null,
            height: null,
            chartDataSource: null,
            //index:0,
        },
        {
            divInfo: null,
            width: null,
            chartSize: null,
            height: null,
            chartDataSource: null,
        //index:0,
        },
        {
            divInfo: null,
            width: null,
            chartSize: null,
            height: null,
            chartDataSource: null,
            //index:0,
        },
        {
            divInfo: null,
            width: null,
            chartSize: null,
            height: null,
            chartDataSource: null,
            //index:0,
        },
        {
            divInfo: null,
            width: null,
            chartSize: null,
            height: null,
            chartDataSource: null,
            //index:0,
        },
        ];
        this.multiViewOptions = options.multiViewOptions || {
            viewIndex: ko.observable(0),
            viewCount: 0,
            PageChanged: options.multiViewOptions.PageChanged, //hcLee 2015 07 20 V14.1-V15.1  
        };
    };
    var sideOverlayVisible = ko.observable(false);
    var PageHistory= [];
    var commonOverlayOptions = {
        width: 80,
        height: 100,
        shading: false,
        //hoverStateEnabled:true,
        animation: {
            show: { type: "fade", duration: 150, from: 0, to: 1 },
            hide: { type: "fade", duration: 150, from: 1, to: 0 }
        }
    };
    cl.Paging = {
        _adapter: null,
        _viewIndex: null,
        _viewCount: null,

        setAdapter: function( chartLayout ) {
            this._adapter = chartLayout;
            if (_.isNull(this._adapter)) {
                this._viewIndex = null;
                this._viewCount = null;
                this.sideOverlayVisible(false);
            }
            else {
                this._viewIndex = chartLayout.multiViewOptions.viewIndex;
                this._viewCount = chartLayout.multiViewOptions.viewCount;                
                this.sideOverlayVisible(true);
            }
        },
        
        sideOverlayVisible: sideOverlayVisible,

        leftNavigationOverlayOptions: $.extend({
            visible: sideOverlayVisible,
            position: ko.observable()
        }, commonOverlayOptions ),

        hideNextButton: ko.observable( false ),
        hidePrevButton: ko.observable( false ),

        rightNavigationOverlayOptions: $.extend({
            visible: sideOverlayVisible,
            position: ko.observable()
        }, commonOverlayOptions ),

        onClickPrevButton: function() {
            var paging = BWA.ChartLayout.Paging;
            if (_.isNull(paging._viewIndex) || _.isNull(paging._viewCount)) {
                return;
            }
            var index = paging._viewIndex() - 1;
            if (index < 0) {
                return;
            }
            //paging._adapter.fullscreenElement.index = index;
            paging._viewIndex(index);
            paging.enableButtons();
            /*
            $.each(paging._adapter.divs, function (i, e) {
                (function (divInfo) {
                    $(['#', divInfo.id].join('')).dblclick(function (event) {
                        paging._adapter.toggleFullScreenSelector(divInfo);
                        event.preventDefault();
                        return false;
                    });
                })(e);
            });*/

            /*
            _.each(PageHistory, function (x) {
                if (x == index) return;
            });
            // 처음이다*/
            if (!PageHistory.indexOf(index) < 0) {
                PageHistory.push(index);
            }
            if (paging._adapter.multiViewOptions.PageChanged) paging._adapter.multiViewOptions.PageChanged(); // hcLee 2015 07 20 
        },
        onClickRightButton: function() {
            var paging = BWA.ChartLayout.Paging;
            if (_.isNull(paging._viewIndex) || _.isNull(paging._viewCount)) {
                return;
            }
            var index = paging._viewIndex() + 1;
            if (paging._viewCount <= index) {
                return;
            }
            paging._viewIndex(index);
            paging.enableButtons();
            //paging._adapter.fullscreenElement.index = index;

            /*
            $.each(paging._adapter.divs, function (i, e) {
                (function (divInfo) {
                    $(['#', divInfo.id].join('')).dblclick(function (event) {
                        paging._adapter.toggleFullScreenSelector(divInfo);
                        event.preventDefault();
                        return false;
                    });
                })(e);
            });*/

            //hcLee 2015 07 20 V14.1-V15.1  시작
            /*var first = true;
            _.each(PageHistory, function (x) {
                if (x == index) first = false;
            });
            if (first == false) return;*/

            // 최초클릭인 경우만 처리            
            if (!PageHistory.indexOf(index) < 0) {
                PageHistory.push(index);
            }
            if (paging._adapter.multiViewOptions.PageChanged) paging._adapter.multiViewOptions.PageChanged(); // hcLee 2015 07 20

            $.each(paging._adapter.divs[index], function (i, e) {
                (function (divInfo) {
                    var div = $(['#', divInfo.id].join(''));
                    div.unbind('dblclick'); //jhLee 2016 07 12
                    div.dblclick(function (event) {
                        paging._adapter.toggleFullScreenSelector(divInfo, index);
                        event.preventDefault();
                        return false;
                    });
                })(e);
            });
            //hcLee 2015 07 20 V14.1-V15.1  끝
        },
        enableButtons: function() {
            var paging = BWA.ChartLayout.Paging;
            if (_.isNull(paging._viewIndex) || _.isNull(paging._viewCount)) {
                return;
            }

            paging.hidePrevButton(false);
            paging.hideNextButton(false);
            if (paging._viewIndex() === 0) {
                paging.hidePrevButton(true);
            } 
            if (paging._viewIndex() === paging._viewCount - 1) {
                paging.hideNextButton(true);            
            }                

        },
        leftNavigationOverlayButtonOptions: {
            icon: 'arrowleft',
            width: '100%',
            height: '100%'
        },

        rightNavigationOverlayButtonOptions: {
            icon: 'arrowright',
            width: '100%',
            height: '100%'
        }
    };

    cl.prototype.initialize = function () {
        if (this.initialized === true) {
            return;
        }
        //var paging = BWA.ChartLayout.Paging;
        console.log('initialize');
        var self = this;
        $.each(self.divs[0], function (i, e) {  //hcLee 2015 07 20 V14.1-V15.1 
            (function (divInfo) {
                var div = $(['#', divInfo.id].join(''));
                    div.unbind('dblclick'); //jhLee 2016 07 12
                    div.dblclick(function (event) {
                        self.toggleFullScreenSelector(divInfo, 0);
                        event.preventDefault();
                        return false;
                    });
            })(e);
        });
        /*
        $.each(self.divs[1], function (i, e) {  //hcLee 2015 07 20 V14.1-V15.1 
            (function (divInfo) {
                var div = $(['#', divInfo.id].join(''));
                div.unbind('dblclick'); //jhLee 2016 07 12
                div.dblclick(function (event) {
                    self.toggleFullScreenSelector(divInfo, 1);
                    event.preventDefault();
                    return false;
                });
            })(e);
        });
        $.each(self.divs[2], function (i, e) {  //hcLee 2015 07 20 V14.1-V15.1 
            (function (divInfo) {
                var div = $(['#', divInfo.id].join(''));
                div.unbind('dblclick'); //jhLee 2016 07 12
                div.dblclick(function (event) {
                    self.toggleFullScreenSelector(divInfo, 2);
                    event.preventDefault();
                    return false;
                });
            })(e);
        });*/

        this.initialized = true;
    };

    cl.prototype.onShown = function() {

        var paging = BWA.ChartLayout.Paging;

        paging.setAdapter(this);

        paging.leftNavigationOverlayOptions.position({ my: 'right', at: 'left', of: $('#mainContents'), offset: '-20 -30' });
        paging.rightNavigationOverlayOptions.position({ my: 'left', at: 'right', of: $('#mainContents'), offset: '20 -30' });


        if (this.multiViewOptions.viewCount <= 1) {
            paging.hidePrevButton(true);
            paging.hideNextButton(true);
            paging.sideOverlayVisible(false);
        }
        else {
            paging.sideOverlayVisible(true);
        }

        if (this.multiViewOptions.viewCount > 1)
            paging.enableButtons();
    };

    cl.prototype.onHidden = function() {
        var paging = BWA.ChartLayout.Paging;

        paging.setAdapter(null);

    };

    cl.prototype.getChartInstance = function(divInfo) {

        var chart = null;
        var chartElement = _.isString(divInfo.chartId) ? $(['#', divInfo.chartId].join('')) : null;
        if (chartElement) {
            chart = chartElement[divInfo.widgetChartName || 'dxChart']('instance');
        }
        return chart;
    }

    cl.prototype.toggleFullScreenSelector = function(divInfo, index) {

        var self = this;
        console.log(divInfo);
        var jqDiv = $(['#', divInfo.id].join(''));

        var chart = this.getChartInstance(divInfo);
        if (_.isNull(chart)) {
            return;
        }

        /*if (this.fullscreenElement.index != index) {
            //this.fullscreenElement.index = index;
            return;
        }*/

        var renderOptions = {
            force: true,
            animate: true,
            asyncSeriesRendering: false
        };
        if (this.fullscreenElement[index].divInfo === null) { //hcLee 2015 07 20 V14.1-V15.1  fullscreenElement[index]
            this.fullscreenElement[index].width = jqDiv.css('width'); //hcLee 2015 07 20 V14.1-V15.1  fullscreenElement[index]
            this.fullscreenElement[index].height = jqDiv.css('height');//hcLee 2015 07 20 V14.1-V15.1  fullscreenElement[index]
            this.fullscreenElement[index].divInfo = divInfo;//hcLee 2015 07 20 V14.1-V15.1  fullscreenElement[index]
            if (_.isNull(chart) === false) {
                this.fullscreenElement[index].chartSize = chart.getSize();//hcLee 2015 07 20 V14.1-V15.1  fullscreenElement[index]
                chart.option('animation', {
                    duration: 200,
                    //enabled: false
                });
            }
            var promises = [];
            $.each(self.divs[index], function (i, div) {  //hcLee 2015 07 20 V14.1-V15.1  divs[index]

                if (divInfo.id !== div.id) {
                    var jq = $(['#', div.id].join(''));
                    var p = jq.animate({
                        opacity: 0
                    }, {
                        duration: 150,
                    }).promise();
                    promises.push(p);
                }
            });

            $.when.apply(this, promises).done(function() {

                var tempPosition = {
                    marginLeft: jqDiv.css('marginLeft'),
                    marginTop: jqDiv.css('marginTop')
                }
                var offset = jqDiv.offset();
                var parentOffset = jqDiv.parent().offset();

                var duration = 100;
                if (_.isEqual(offset, parentOffset)) {
                    duration = 0;
                }

                jqDiv.animate({
                    marginLeft: parentOffset.left - offset.left,
                    marginTop: parentOffset.top - offset.top 
                }, {
                    duration: duration,

                    complete: function() {

                        $.each(self.divs[index], function (i, div) { //hcLee 2015 07 20 V14.1-V15.1  divs[index]
                            if (divInfo.id !== div.id) {
                                $(['#', div.id].join('')).css('display', 'none');
                            }
                        });
                        jqDiv.css($.extend(tempPosition, {
                            'width': '100%',
                            'height': '100%',
                        }));
                        if (_.isNull(chart) === false) chart.render(renderOptions);                        
                    }
                });
            });

            console.log(this.fullscreenElement[index]); //hcLee 2015 07 20 V14.1-V15.1  fullscreenElement[index]
        }
        else {

            jqDiv.css({
                'width': self.fullscreenElement[index].width, //hcLee 2015 07 20 V14.1-V15.1  fullscreenElement[index]
                'height': self.fullscreenElement[index].height //hcLee 2015 07 20 V14.1-V15.1  fullscreenElement[index]
            });
            if (_.isNull(chart) === false) chart.render(renderOptions);
            
            $.each(self.divs[index], function (i, div) { //hcLee 2015 07 20 V14.1-V15.1  divs[index]
                if (self.fullscreenElement[index].id !== div.id) { //hcLee 2015 07 20 V14.1-V15.1  fullscreenElement[index]

                    var jq = $(['#', div.id].join(''));
                    jq.css('display', 'inline');                                        
                    jq.animate({
                        opacity: 1
                    }, {
                        duration: 400,
                        done: function() {
                            var otherChart = self.getChartInstance(div);
                            if (_.isNull(otherChart)) {
                                return;
                            }
                            otherChart.render({
                                force: true,
                                animate: false,
                                asyncSeriesRendering: false
                            });
                        }
                    });
                }
            });


            this.fullscreenElement[index].divInfo = null; //hcLee 2015 07 20 V14.1-V15.1  fullscreenElement[index]
        }
    }
});

                //jqDiv.animate({
                //        width: '100%',
                //        height: '100%'
                //    }, {
                //        easing: 'easeOutQuart',
                //        duration: 500,
                //        progress: function() {
                //            chart._render();
                //        },
                //        complete: function() {
                //            jqDiv.css('width', '100%');
                //            jqDiv.css('height', '100%');                                    

                //        }
                //    } 
                //);

            //jqDiv.animate( 
            //    _.pick( this.fullscreenElement, 'width', 'height' ), 
            //    {
            //        easing: 'easeOutQuart',
            //        duration: 0,
            //        progress: function() {
                    
            //            chart._render();
            //        }, 
            //        complete: function() {

            //            jChart.css('width', self.fullscreenElement.width);
            //            jChart.css('height', self.fullscreenElement.height);

            //            $.each(self.divs, function(i, div) {
            //                if (self.fullscreenElement.id !== div.id) {

            //                    var jq = $(['#', div.id].join(''));
            //                    jq.css('display', 'inline');                                        
            //                    jq.animate({
            //                        opacity: 1
            //                    }, {
            //                        duration: 400,
            //                        done: function() {
            //                        }
            //                    });
            //                }
            //            });

            //        }   
            //    }
            //);


            //jChart.css('width', this.fullscreenElement.width);
            //jChart.css('height', this.fullscreenElement.height);