<commit_before>var TickDisplay = function() {
    return {
        reset: function() {
            var $self = this;
            $self.contract_barrier = null;
            $self.applicable_ticks = [];
            $self.number_of_ticks = null;
            $self.ev.close();
            $self.chart.destroy();
        },
        initialize: function(data) {
            var $self = this;

            // setting up globals
            $self.number_of_ticks = parseInt(data.number_of_ticks);
            $self.symbol = data.symbol;
            $self.display_symbol = data.display_symbol;
            $self.contract_start_ms = parseInt(data.contract_start * 1000);
            $self.contract_category = data.contract_category;
            $self.set_barrier = ($self.contract_category.match('digits')) ? false : true;
            $self.display_decimals = data.display_decimals || 2;
            var tick_frequency = 5;

            if (data.show_contract_result) {
                $self.show_contract_result = true;
                $self.contract_sentiment = data.contract_sentiment;
                $self.price = parseFloat(data.price);
                $self.payout = parseFloat(data.payout);
            }

            var minimize = data.show_contract_result;

            $self.set_x_indicators();
            $self.initialize_chart({
                plot_from: data.previous_tick_epoch * 1000,
                plot_to: new Date((parseInt(data.contract_start) + parseInt(($self.number_of_ticks+2)*tick_frequency)) * 1000).getTime(),
                minimize: minimize,
                width: data.width ? data.width : undefined
            });
        },
        set_x_indicators: function() {
            var $self = this;

            var exit_tick_index = $self.number_of_ticks - 1;
            if ($self.contract_category.match('asian')) {
                $self.ticks_needed = $self.number_of_ticks;
                $self.x_indicators = {
                    '_0': { label: 'Tick 1', id: 'start_tick'},
                };
                $self.x_indicators['_' + exit_tick_index] = {
                    label: 'Exit Spot',
                    id: 'exit_tick',
                };
            } else if ($self.contract_category.match('callput')) {
                $self.ticks_needed = $self.number_of_ticks + 1;
                $self.x_indicators = {
                    '_0': { label: 'Entry Spot', id: 'entry_tick'},
                };
                $self.x_indicators['_' + $self.number_of_ticks] = {
                    label: 'Exit Spot',
                    id: 'exit_tick',
                };
            } else if ($self.contract_category.match('digits')) {
                $self.ticks_needed = $self.number_of_ticks;
                $self.x_indicators = {
                    '_0': { label: 'Tick 1', id: 'start_tick'},
                };
                $self.x_indicators['_' + exit_tick_index] = {
                    label:  'Tick ' + $self.number_of_ticks,
                    id: 'last_tick',
                };
            } else {
                $self.x_indicators = {};
            }

        },
        initialize_chart: function(config) {
            var $self = this;

            $self.chart = new Highcharts.Chart({
                chart: {
                    type: 'line',
                    renderTo: 'tick_chart',
                    width: config.width ? config.width : (config.minimize ? 394 : null),
                    height: config.minimize ? 143 : null,
                    backgroundColor: null,
                    events: { load: $self.plot(config.plot_from, config.plot_to) },
                },
                credits: {enabled: false},
                tooltip: {
                    formatter: function () {
                        var that = this;
                        var new_y = that.y.toFixed($self.display_decimals);
                        var mom = moment.utc($self.applicable_ticks[that.x].epoch*1000).format("dddd, MMM D, HH:mm:ss");

                        return mom + "
" + $self.display_symbol + " " + new_y;
                    },
                },
                xAxis: {
                    type: 'linear',
                    min: 0,
                    max: $self.number_of_ticks + 1,
                    labels: { enabled: false, }
                },
                yAxis: {
                    opposite: false,
                    labels: {
                        align: 'left',
                        x: 0,
                    },
                    title: ''
                },
                series: [{
                    data: [],
                }],
                title: '',
                exporting: {enabled: false, enableImages: false},
                legend: {enabled: false},
            });
        },
        plot: function(plot_from, plot_to) {
            var $self = this;

            var plot_from_moment = moment(plot_from).utc();
            var plot_to_moment = moment(plot_to).utc();
            var contract_start_moment = moment($self.contract_start_ms).utc();
            $self.counter = 0;
            $self.applicable_ticks = [];

            var symbol = $self.symbol;
            var stream_url = window.location.protocol + '//' + page.settings.get('streaming_server');
            stream_url += "/stream/ticks/" + symbol + "/" + plot_from_moment.unix() + "/" + plot_to_moment.unix();
            $self.ev = new EventSource(stream_url, { withCredentials: true });

            $self.ev.onmessage = function(msg) {
                if ($self.applicable_ticks.length >= $self.ticks_needed) {
                    $self.ev.close();
                    $self.evaluate_contract_outcome();
                    return;
                }

                var data = JSON.parse(msg.data);
                if (data && !(data[0] instanceof Array)) {
                    data = [ data ];
                }
                if (data) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i][0] === 'tick') {
                            var tick = {
                                epoch: parseInt(data[i][1]),
                                quote: parseFloat(data[i][2])
                            };

                            if (tick.epoch > contract_start_moment.unix()) {
                                if ($self.applicable_ticks.length >= $self.ticks_needed) {
                                    $self.ev.close();
                                    $self.evaluate_contract_outcome();
                                    return;
                                } else {
                                    if (!$self.chart) return;
                                    if (!$self.chart.series) return;
                                    $self.chart.series[0].addPoint([$self.counter, tick.quote], true, false);
                                    $self.applicable_ticks.push(tick);
                                    var indicator_key = '_' + $self.counter;
                                    if (typeof $self.x_indicators[indicator_key] !== 'undefined') {
                                        $self.x_indicators[indicator_key]['index'] = $self.counter;
                                        $self.add($self.x_indicators[indicator_key]);
                                    }

                                    $self.add_barrier();
                                    $self.apply_chart_background_color(tick);
                                    $self.counter++;
                                }
                            }

                        }
                    }
                }
            };
            $self.ev.onerror = function(e) {$self.ev.close(); };
        },
        apply_chart_background_color: function(tick) {
            var $self = this;

            var chart_container = $('#tick_chart');
            if ($self.contract_sentiment === 'up') {
                if (tick.quote > $self.contract_barrier) {
                    chart_container.css('background-color', 'rgba(46,136,54,0.198039)');
                } else {
                    chart_container.css('background-color', 'rgba(204,0,0,0.098039)');
                }
            } else if ($self.contract_sentiment === 'down') {
                if (tick.quote < $self.contract_barrier) {
                    chart_container.css('background-color', 'rgba(46,136,54,0.198039)');
                } else {
                    chart_container.css('background-color', 'rgba(204,0,0,0.098039)');
                }
            }
        },
        add_barrier: function() {
            var $self = this;

            if (!$self.set_barrier) {
                return;
            }

            var barrier_type = $self.contract_category.match('asian') ? 'asian' : 'static';

            if (barrier_type === 'static') {
                var barrier_tick = $self.applicable_ticks[0];
                $self.chart.yAxis[0].addPlotLine({
                    id: 'tick-barrier',
                    value: barrier_tick.quote,
                    label: {text: 'Barrier ('+barrier_tick.quote+')', align: 'center'},
                    color: 'green',
                    width: 2,
                });
                $self.contract_barrier = barrier_tick.quote;
                $self.set_barrier = false;
            }

            if (barrier_type === 'asian') {
                var total = 0;
                for (var i=0; i < $self.applicable_ticks.length; i++) {
                    total += parseFloat($self.applicable_ticks[i].quote);
                }
                var calc_barrier =  total/$self.applicable_ticks.length;
                calc_barrier = calc_barrier.toFixed(parseInt($self.display_decimals) + 1); // round calculated barrier

                $self.chart.yAxis[0].removePlotLine('tick-barrier');
                $self.chart.yAxis[0].addPlotLine({
                    id: 'tick-barrier',
                    value: calc_barrier,
                    color: 'green',
                    label: {
                        text: 'Average ('+calc_barrier+')',
                        align: 'center'
                    },
                    width: 2,
                });
                $self.contract_barrier = calc_barrier;
            }
        },
        add: function(indicator) {
            var $self = this;

            $self.chart.xAxis[0].addPlotLine({
               value: indicator.index,
               id: indicator.id,
               label: {text: indicator.label},
               color: '#e98024',
               width: 2,
            });
        },
        evaluate_contract_outcome: function() {
            var $self = this;

            if (!$self.contract_barrier) {
                return; // can't do anything without barrier
            }

            var exit_tick_index = $self.applicable_ticks.length - 1;
            var exit_spot = $self.applicable_ticks[exit_tick_index].quote;

            if ($self.contract_sentiment === 'up') {
                if (exit_spot > $self.contract_barrier) {
                    $self.win();
                } else {
                    $self.lose();
                }
            } else if ($self.contract_sentiment === 'down') {
                if (exit_spot < $self.contract_barrier) {
                    $self.win();
                } else {
                    $self.lose();
                }
            }

        },
        win: function() {
            var $self = this;

            var profit = $self.payout - $self.price;
            $self.update_ui($self.payout, profit, text.localize('This contract won'));
        },
        lose: function() {
            var $self = this;
            $self.update_ui(0, -$self.price, text.localize('This contract lost'));
        },
        update_ui: function(final_price, pnl, contract_status) {
            var $self = this;

            $('#bet-confirm-header').text(text.localize(contract_status));
            $('#contract-outcome-buyprice').text($self.to_monetary_format($self.price));
            $('#contract-outcome-payout').text($self.to_monetary_format(final_price));

            if (pnl > 0) {
                $('#contract-outcome-label').removeClass('standin loss').addClass('standout profit').text(text.localize('Profit'));
                $('#contract-outcome-profit').removeClass('standin loss').addClass('standout profit').text($self.to_monetary_format(pnl));
            } else {
                $('#contract-outcome-label').removeClass('standout profit').addClass('standin loss').text(text.localize('Loss'));
                $('#contract-outcome-profit').removeClass('standout profit').addClass('standin loss').text($self.to_monetary_format(pnl));
            }
            $('#confirmation_table').hide();
            $('#contract-outcome-details').show();
        },
        to_monetary_format: function(number) {
            return number.toFixed(2);
        }
    };
}();
<commit_msg>fixed tick_trade tooltip<commit_after>var TickDisplay = function() {
    return {
        reset: function() {
            var $self = this;
            $self.contract_barrier = null;
            $self.applicable_ticks = [];
            $self.number_of_ticks = null;
            $self.ev.close();
            $self.chart.destroy();
        },
        initialize: function(data) {
            var $self = this;

            // setting up globals
            $self.number_of_ticks = parseInt(data.number_of_ticks);
            $self.symbol = data.symbol;
            $self.display_symbol = data.display_symbol;
            $self.contract_start_ms = parseInt(data.contract_start * 1000);
            $self.contract_category = data.contract_category;
            $self.set_barrier = ($self.contract_category.match('digits')) ? false : true;
            $self.display_decimals = data.display_decimals || 2;
            var tick_frequency = 5;

            if (data.show_contract_result) {
                $self.show_contract_result = true;
                $self.contract_sentiment = data.contract_sentiment;
                $self.price = parseFloat(data.price);
                $self.payout = parseFloat(data.payout);
            }

            var minimize = data.show_contract_result;

            $self.set_x_indicators();
            $self.initialize_chart({
                plot_from: data.previous_tick_epoch * 1000,
                plot_to: new Date((parseInt(data.contract_start) + parseInt(($self.number_of_ticks+2)*tick_frequency)) * 1000).getTime(),
                minimize: minimize,
                width: data.width ? data.width : undefined
            });
        },
        set_x_indicators: function() {
            var $self = this;

            var exit_tick_index = $self.number_of_ticks - 1;
            if ($self.contract_category.match('asian')) {
                $self.ticks_needed = $self.number_of_ticks;
                $self.x_indicators = {
                    '_0': { label: 'Tick 1', id: 'start_tick'},
                };
                $self.x_indicators['_' + exit_tick_index] = {
                    label: 'Exit Spot',
                    id: 'exit_tick',
                };
            } else if ($self.contract_category.match('callput')) {
                $self.ticks_needed = $self.number_of_ticks + 1;
                $self.x_indicators = {
                    '_0': { label: 'Entry Spot', id: 'entry_tick'},
                };
                $self.x_indicators['_' + $self.number_of_ticks] = {
                    label: 'Exit Spot',
                    id: 'exit_tick',
                };
            } else if ($self.contract_category.match('digits')) {
                $self.ticks_needed = $self.number_of_ticks;
                $self.x_indicators = {
                    '_0': { label: 'Tick 1', id: 'start_tick'},
                };
                $self.x_indicators['_' + exit_tick_index] = {
                    label:  'Tick ' + $self.number_of_ticks,
                    id: 'last_tick',
                };
            } else {
                $self.x_indicators = {};
            }

        },
        initialize_chart: function(config) {
            var $self = this;

            $self.chart = new Highcharts.Chart({
                chart: {
                    type: 'line',
                    renderTo: 'tick_chart',
                    width: config.width ? config.width : (config.minimize ? 394 : null),
                    height: config.minimize ? 143 : null,
                    backgroundColor: null,
                    events: { load: $self.plot(config.plot_from, config.plot_to) },
                },
                credits: {enabled: false},
                tooltip: {
                    formatter: function () {
                        var that = this;
                        var new_y = that.y.toFixed($self.display_decimals);
                        var mom = moment.utc($self.applicable_ticks[that.x].epoch*1000).format("dddd, MMM D, HH:mm:ss");
                        return mom + "
" + $self.display_symbol + " " + new_y;
                    },
                },
                xAxis: {
                    type: 'linear',
                    min: 0,
                    max: $self.number_of_ticks + 1,
                    labels: { enabled: false, }
                },
                yAxis: {
                    opposite: false,
                    labels: {
                        align: 'left',
                        x: 0,
                    },
                    title: ''
                },
                series: [{
                    data: [],
                }],
                title: '',
                exporting: {enabled: false, enableImages: false},
                legend: {enabled: false},
            });
        },
        plot: function(plot_from, plot_to) {
            var $self = this;

            var plot_from_moment = moment(plot_from).utc();
            var plot_to_moment = moment(plot_to).utc();
            var contract_start_moment = moment($self.contract_start_ms).utc();
            $self.counter = 0;
            $self.applicable_ticks = [];

            var symbol = $self.symbol;
            var stream_url = window.location.protocol + '//' + page.settings.get('streaming_server');
            stream_url += "/stream/ticks/" + symbol + "/" + plot_from_moment.unix() + "/" + plot_to_moment.unix();
            $self.ev = new EventSource(stream_url, { withCredentials: true });

            $self.ev.onmessage = function(msg) {
                if ($self.applicable_ticks.length >= $self.ticks_needed) {
                    $self.ev.close();
                    $self.evaluate_contract_outcome();
                    return;
                }

                var data = JSON.parse(msg.data);
                if (data && !(data[0] instanceof Array)) {
                    data = [ data ];
                }
                if (data) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i][0] === 'tick') {
                            var tick = {
                                epoch: parseInt(data[i][1]),
                                quote: parseFloat(data[i][2])
                            };

                            if (tick.epoch > contract_start_moment.unix()) {
                                if ($self.applicable_ticks.length >= $self.ticks_needed) {
                                    $self.ev.close();
                                    $self.evaluate_contract_outcome();
                                    return;
                                } else {
                                    if (!$self.chart) return;
                                    if (!$self.chart.series) return;
                                    $self.chart.series[0].addPoint([$self.counter, tick.quote], true, false);
                                    $self.applicable_ticks.push(tick);
                                    var indicator_key = '_' + $self.counter;
                                    if (typeof $self.x_indicators[indicator_key] !== 'undefined') {
                                        $self.x_indicators[indicator_key]['index'] = $self.counter;
                                        $self.add($self.x_indicators[indicator_key]);
                                    }

                                    $self.add_barrier();
                                    $self.apply_chart_background_color(tick);
                                    $self.counter++;
                                }
                            }

                        }
                    }
                }
            };
            $self.ev.onerror = function(e) {$self.ev.close(); };
        },
        apply_chart_background_color: function(tick) {
            var $self = this;

            var chart_container = $('#tick_chart');
            if ($self.contract_sentiment === 'up') {
                if (tick.quote > $self.contract_barrier) {
                    chart_container.css('background-color', 'rgba(46,136,54,0.198039)');
                } else {
                    chart_container.css('background-color', 'rgba(204,0,0,0.098039)');
                }
            } else if ($self.contract_sentiment === 'down') {
                if (tick.quote < $self.contract_barrier) {
                    chart_container.css('background-color', 'rgba(46,136,54,0.198039)');
                } else {
                    chart_container.css('background-color', 'rgba(204,0,0,0.098039)');
                }
            }
        },
        add_barrier: function() {
            var $self = this;

            if (!$self.set_barrier) {
                return;
            }

            var barrier_type = $self.contract_category.match('asian') ? 'asian' : 'static';

            if (barrier_type === 'static') {
                var barrier_tick = $self.applicable_ticks[0];
                $self.chart.yAxis[0].addPlotLine({
                    id: 'tick-barrier',
                    value: barrier_tick.quote,
                    label: {text: 'Barrier ('+barrier_tick.quote+')', align: 'center'},
                    color: 'green',
                    width: 2,
                });
                $self.contract_barrier = barrier_tick.quote;
                $self.set_barrier = false;
            }

            if (barrier_type === 'asian') {
                var total = 0;
                for (var i=0; i < $self.applicable_ticks.length; i++) {
                    total += parseFloat($self.applicable_ticks[i].quote);
                }
                var calc_barrier =  total/$self.applicable_ticks.length;
                calc_barrier = calc_barrier.toFixed(parseInt($self.display_decimals) + 1); // round calculated barrier

                $self.chart.yAxis[0].removePlotLine('tick-barrier');
                $self.chart.yAxis[0].addPlotLine({
                    id: 'tick-barrier',
                    value: calc_barrier,
                    color: 'green',
                    label: {
                        text: 'Average ('+calc_barrier+')',
                        align: 'center'
                    },
                    width: 2,
                });
                $self.contract_barrier = calc_barrier;
            }
        },
        add: function(indicator) {
            var $self = this;

            $self.chart.xAxis[0].addPlotLine({
               value: indicator.index,
               id: indicator.id,
               label: {text: indicator.label},
               color: '#e98024',
               width: 2,
            });
        },
        evaluate_contract_outcome: function() {
            var $self = this;

            if (!$self.contract_barrier) {
                return; // can't do anything without barrier
            }

            var exit_tick_index = $self.applicable_ticks.length - 1;
            var exit_spot = $self.applicable_ticks[exit_tick_index].quote;

            if ($self.contract_sentiment === 'up') {
                if (exit_spot > $self.contract_barrier) {
                    $self.win();
                } else {
                    $self.lose();
                }
            } else if ($self.contract_sentiment === 'down') {
                if (exit_spot < $self.contract_barrier) {
                    $self.win();
                } else {
                    $self.lose();
                }
            }

        },
        win: function() {
            var $self = this;

            var profit = $self.payout - $self.price;
            $self.update_ui($self.payout, profit, text.localize('This contract won'));
        },
        lose: function() {
            var $self = this;
            $self.update_ui(0, -$self.price, text.localize('This contract lost'));
        },
        update_ui: function(final_price, pnl, contract_status) {
            var $self = this;

            $('#bet-confirm-header').text(text.localize(contract_status));
            $('#contract-outcome-buyprice').text($self.to_monetary_format($self.price));
            $('#contract-outcome-payout').text($self.to_monetary_format(final_price));

            if (pnl > 0) {
                $('#contract-outcome-label').removeClass('standin loss').addClass('standout profit').text(text.localize('Profit'));
                $('#contract-outcome-profit').removeClass('standin loss').addClass('standout profit').text($self.to_monetary_format(pnl));
            } else {
                $('#contract-outcome-label').removeClass('standout profit').addClass('standin loss').text(text.localize('Loss'));
                $('#contract-outcome-profit').removeClass('standout profit').addClass('standin loss').text($self.to_monetary_format(pnl));
            }
            $('#confirmation_table').hide();
            $('#contract-outcome-details').show();
        },
        to_monetary_format: function(number) {
            return number.toFixed(2);
        }
    };
}();
<|endoftext|>


<commit_before>/*
 * Purchase object that handles all the functions related to
 * contract purchase response
 */

var Purchase = (function () {
    'use strict';

    var purchase_data = {};

    var display = function (details) {
        purchase_data = details;

        var receipt = details['buy'],
            passthrough = details['echo_req']['passthrough'],
            container = document.getElementById('contract_confirmation_container'),
            message_container = document.getElementById('confirmation_message'),
            heading = document.getElementById('contract_purchase_heading'),
            descr = document.getElementById('contract_purchase_descr'),
            reference = document.getElementById('contract_purchase_reference'),
            chart = document.getElementById('tick_chart'),
            balance = document.getElementById('contract_purchase_balance'),
            payout = document.getElementById('contract_purchase_payout'),
            cost = document.getElementById('contract_purchase_cost'),
            profit = document.getElementById('contract_purchase_profit'),
            spots = document.getElementById('contract_purchase_spots'),
            confirmation_error = document.getElementById('confirmation_error'),
            contracts_list = document.getElementById('contracts_list'),
            button = document.getElementById('contract_purchase_button');

        var error = details['error'];
        var show_chart = !error && passthrough['duration']<=10 && passthrough['duration_unit']==='t' && (sessionStorage.formname === 'risefall' || sessionStorage.formname === 'higherlower' || sessionStorage.formname === 'asian');

        contracts_list.style.display = 'none';

        if (error) {
            container.style.display = 'block';
            message_container.hide();
            confirmation_error.show();
            confirmation_error.innerHTML = (/ClientUnwelcome/.test(error.code) ? error['message'] + ' ' + text.localize('Authorise your account.' + '') : error['message']);
        } else {
            var guideBtn = document.getElementById('guideBtn');
            if(guideBtn) {
                guideBtn.style.display = 'none';
            }
            container.style.display = 'table-row';
            message_container.show();
            confirmation_error.hide();

            heading.textContent = Content.localize().textContractConfirmationHeading;
            descr.textContent = receipt['longcode'];
            reference.textContent = Content.localize().textContractConfirmationReference + ' ' + receipt['transaction_id'];

            var payout_value, cost_value, profit_value;

            if(passthrough['basis'] === "payout"){
                payout_value = passthrough['amount'];
                cost_value = passthrough['ask-price'];
            }
            else{
                cost_value = passthrough['amount'];
                payout_value = receipt['payout'];
            }
            profit_value = Math.round((payout_value - cost_value)*100)/100;

            if(sessionStorage.getItem('formname')==='spreads'){
                payout.innerHTML = Content.localize().textStopLoss + '
' + receipt.stop_loss_level + '
';
                cost.innerHTML = Content.localize().textAmountPerPoint + '
' + receipt.amount_per_point + '
';
                profit.innerHTML = Content.localize().textStopProfit + '
' + receipt.stop_profit_level + '
';
            }
            else {
                payout.innerHTML = Content.localize().textContractConfirmationPayout + '
' + payout_value + '
';
                cost.innerHTML = Content.localize().textContractConfirmationCost + '
' + cost_value + '
';
                profit.innerHTML = Content.localize().textContractConfirmationProfit + '
' + profit_value + '
';
            }

            balance.textContent = Content.localize().textContractConfirmationBalance + ' ' + TUser.get().currency + ' ' + Math.round(receipt['balance_after']*100)/100;

            if(show_chart){
                chart.show();
            }
            else{
                chart.hide();
            }

            if(Contract.form() === 'digits'){
                spots.textContent = '';
                spots.className = '';
                spots.show();
            }
            else{
                spots.hide();
            }

            if(Contract.form() !== 'digits' && !show_chart){
                button.textContent = Content.localize().textContractConfirmationButton;
                button.setAttribute('contract_id', receipt['contract_id']);
                button.show();
                $('.open_contract_detailsws').attr('contract_id', receipt['contract_id']).removeClass('invisible');
            }
            else{
                button.hide();
                $('.open_contract_detailsws').addClass('invisible');
            }
        }

        if(show_chart){
            var contract_sentiment;
            if(passthrough['contract_type']==='CALL' || passthrough['contract_type']==='ASIANU'){
                contract_sentiment = 'up';
            }
            else{
                contract_sentiment = 'down';
            }

            var tick_spots = Tick.spots();
            var last_quote = tick_spots[Object.keys(tick_spots)[0]];
            var decimal_points = last_quote.toString().split('.')[1].length;

            WSTickDisplay.initialize({
                symbol:passthrough.symbol,
                number_of_ticks:passthrough.duration,
                previous_tick_epoch:receipt['start_time'],
                contract_category:sessionStorage.getItem('formname')==='asian' ? 'asian' : 'callput',
                display_symbol:Symbols.getName(passthrough.symbol),
                contract_start:receipt['start_time'],
                display_decimals: decimal_points || 2,
                contract_sentiment:contract_sentiment,
                price:passthrough['ask-price'],
                payout:receipt['payout'],
                show_contract_result:1,
                width: $('#confirmation_message').width(),
            });
            WSTickDisplay.spots_list = {};
        }
    };

    var update_spot_list = function(data){

        if($('#contract_purchase_spots:hidden').length){
            return;
        }

        var duration = purchase_data.echo_req.passthrough['duration'];

        if(!duration){
            return;
        }

        var spots = document.getElementById('contract_purchase_spots');
        var spots2 = Tick.spots();
        var epoches = Object.keys(spots2).sort(function(a,b){return a-b;});
        spots.textContent = '';

        var replace = function(d){d1 = d; return ''+d+'';};
        for(var s=0; s<epoches.length; s++){
            var tick_d = {
                epoch: epoches[s],
                quote: spots2[epoches[s]]
            };

            if(isVisible(spots) && tick_d.epoch && tick_d.epoch > purchase_data.buy.start_time){
                var fragment = document.createElement('div');
                fragment.classList.add('row');

                var el1 = document.createElement('div');
                el1.classList.add('col');
                el1.textContent = Content.localize().textTickResultLabel + " " + (spots.getElementsByClassName('row').length+1);
                fragment.appendChild(el1);

                var el2 = document.createElement('div');
                el2.classList.add('col');
                var date = new Date(tick_d.epoch*1000);
                var hours = date.getUTCHours() < 10 ? '0'+date.getUTCHours() : date.getUTCHours();
                var minutes = date.getUTCMinutes() < 10 ? '0'+date.getUTCMinutes() : date.getUTCMinutes();
                var seconds = date.getUTCSeconds() < 10 ? '0'+date.getUTCSeconds() : date.getUTCSeconds();
                el2.textContent = hours+':'+minutes+':'+seconds;
                fragment.appendChild(el2);

                var d1;
                var tick = tick_d.quote.replace(/\d$/,replace);
                var el3 = document.createElement('div');
                el3.classList.add('col');
                el3.innerHTML = tick;
                fragment.appendChild(el3);

                spots.appendChild(fragment);
                spots.scrollTop = spots.scrollHeight;

                if(d1 && duration===1){
                    var contract_status,
                        final_price,
                        pnl;

                    if  (  purchase_data.echo_req.passthrough.contract_type==="DIGITMATCH" && d1==purchase_data.echo_req.passthrough.barrier || purchase_data.echo_req.passthrough.contract_type==="DIGITDIFF" && d1!=purchase_data.echo_req.passthrough.barrier || purchase_data.echo_req.passthrough.contract_type==="DIGITEVEN" && d1%2===0 || purchase_data.echo_req.passthrough.contract_type==="DIGITODD" && d1%2 || purchase_data.echo_req.passthrough.contract_type==="DIGITOVER" && d1>purchase_data.echo_req.passthrough.barrier || purchase_data.echo_req.passthrough.contract_type==="DIGITUNDER" && d1<purchase_data.echo_req.passthrough.barrier){
                        spots.className = 'won';
                        final_price = $('#contract_purchase_payout p').text();
                        pnl = $('#contract_purchase_cost p').text();
                        contract_status = Content.localize().textContractStatusWon;
                    }
                    else{
                        spots.className = 'lost';
                        final_price = 0;
                        pnl = -$('#contract_purchase_cost p').text();
                        contract_status = Content.localize().textContractStatusLost;
                    }

                    updatePurchaseStatus(final_price, pnl, contract_status);
                }

                duration--;
                if(!duration){
                    purchase_data.echo_req.passthrough['duration'] = 0;
                }
            }

        }

    };

    return {
        display: display,
        update_spot_list: update_spot_list
    };

})();
<commit_msg>polish<commit_after>/*
 * Purchase object that handles all the functions related to
 * contract purchase response
 */

var Purchase = (function () {
    'use strict';

    var purchase_data = {};

    var display = function (details) {
        purchase_data = details;

        var receipt = details['buy'],
            passthrough = details['echo_req']['passthrough'],
            container = document.getElementById('contract_confirmation_container'),
            message_container = document.getElementById('confirmation_message'),
            heading = document.getElementById('contract_purchase_heading'),
            descr = document.getElementById('contract_purchase_descr'),
            reference = document.getElementById('contract_purchase_reference'),
            chart = document.getElementById('tick_chart'),
            balance = document.getElementById('contract_purchase_balance'),
            payout = document.getElementById('contract_purchase_payout'),
            cost = document.getElementById('contract_purchase_cost'),
            profit = document.getElementById('contract_purchase_profit'),
            spots = document.getElementById('contract_purchase_spots'),
            confirmation_error = document.getElementById('confirmation_error'),
            contracts_list = document.getElementById('contracts_list'),
            button = document.getElementById('contract_purchase_button');

        var error = details['error'];
        var show_chart = !error && passthrough['duration']<=10 && passthrough['duration_unit']==='t' && (sessionStorage.formname === 'risefall' || sessionStorage.formname === 'higherlower' || sessionStorage.formname === 'asian');

        contracts_list.style.display = 'none';

        if (error) {
            container.style.display = 'block';
            message_container.hide();
            confirmation_error.show();
            confirmation_error.innerHTML = (/ClientUnwelcome/.test(error.code) ? error['message'] + ' ' + text.localize('Authorise your account.' + '') : error['message']);
        } else {
            var guideBtn = document.getElementById('guideBtn');
            if(guideBtn) {
                guideBtn.style.display = 'none';
            }
            container.style.display = 'table-row';
            message_container.show();
            confirmation_error.hide();

            heading.textContent = Content.localize().textContractConfirmationHeading;
            descr.textContent = receipt['longcode'];
            reference.textContent = Content.localize().textContractConfirmationReference + ' ' + receipt['transaction_id'];

            var payout_value, cost_value, profit_value;

            if(passthrough['basis'] === "payout"){
                payout_value = passthrough['amount'];
                cost_value = passthrough['ask-price'];
            }
            else{
                cost_value = passthrough['amount'];
                payout_value = receipt['payout'];
            }
            profit_value = Math.round((payout_value - cost_value)*100)/100;

            if(sessionStorage.getItem('formname')==='spreads'){
                payout.innerHTML = Content.localize().textStopLoss + '
' + receipt.stop_loss_level + '
';
                cost.innerHTML = Content.localize().textAmountPerPoint + '
' + receipt.amount_per_point + '
';
                profit.innerHTML = Content.localize().textStopProfit + '
' + receipt.stop_profit_level + '
';
            }
            else {
                payout.innerHTML = Content.localize().textContractConfirmationPayout + '
' + payout_value + '
';
                cost.innerHTML = Content.localize().textContractConfirmationCost + '
' + cost_value + '
';
                profit.innerHTML = Content.localize().textContractConfirmationProfit + '
' + profit_value + '
';
            }

            balance.textContent = Content.localize().textContractConfirmationBalance + ' ' + TUser.get().currency + ' ' + Math.round(receipt['balance_after']*100)/100;

            if(show_chart){
                chart.show();
            }
            else{
                chart.hide();
            }

            if(Contract.form() === 'digits'){
                spots.textContent = '';
                spots.className = '';
                spots.show();
            }
            else{
                spots.hide();
            }

            if(Contract.form() !== 'digits' && !show_chart){
                button.textContent = Content.localize().textContractConfirmationButton;
                button.setAttribute('contract_id', receipt['contract_id']);
                button.show();
                $('.open_contract_detailsws').attr('contract_id', receipt['contract_id']).removeClass('invisible');
            }
            else{
                button.hide();
                $('.open_contract_detailsws').addClass('invisible');
            }
        }

        if(show_chart){
            var contract_sentiment;
            if(passthrough['contract_type']==='CALL' || passthrough['contract_type']==='ASIANU'){
                contract_sentiment = 'up';
            }
            else{
                contract_sentiment = 'down';
            }

            //calculate number of decimals needed to display tick-chart according to the spot
            //value of the underlying
            var tick_spots = Tick.spots();
            var decimal_points = 2;
            if ( tick_spots.length > 0 ) {
                var last_quote = tick_spots[Object.keys(tick_spots)[0]].toString();

                if ( last_quote.indexOf(".") != -1 ) {
                    decimal_points = last_quote.split('.')[1].length;
                }
            }

            WSTickDisplay.initialize({
                symbol:passthrough.symbol,
                number_of_ticks:passthrough.duration,
                previous_tick_epoch:receipt['start_time'],
                contract_category:sessionStorage.getItem('formname')==='asian' ? 'asian' : 'callput',
                display_symbol:Symbols.getName(passthrough.symbol),
                contract_start:receipt['start_time'],
                display_decimals: decimal_points,
                contract_sentiment:contract_sentiment,
                price:passthrough['ask-price'],
                payout:receipt['payout'],
                show_contract_result:1,
                width: $('#confirmation_message').width(),
            });
            WSTickDisplay.spots_list = {};
        }
    };

    var update_spot_list = function(data){

        if($('#contract_purchase_spots:hidden').length){
            return;
        }

        var duration = purchase_data.echo_req.passthrough['duration'];

        if(!duration){
            return;
        }

        var spots = document.getElementById('contract_purchase_spots');
        var spots2 = Tick.spots();
        var epoches = Object.keys(spots2).sort(function(a,b){return a-b;});
        spots.textContent = '';

        var replace = function(d){d1 = d; return ''+d+'';};
        for(var s=0; s<epoches.length; s++){
            var tick_d = {
                epoch: epoches[s],
                quote: spots2[epoches[s]]
            };

            if(isVisible(spots) && tick_d.epoch && tick_d.epoch > purchase_data.buy.start_time){
                var fragment = document.createElement('div');
                fragment.classList.add('row');

                var el1 = document.createElement('div');
                el1.classList.add('col');
                el1.textContent = Content.localize().textTickResultLabel + " " + (spots.getElementsByClassName('row').length+1);
                fragment.appendChild(el1);

                var el2 = document.createElement('div');
                el2.classList.add('col');
                var date = new Date(tick_d.epoch*1000);
                var hours = date.getUTCHours() < 10 ? '0'+date.getUTCHours() : date.getUTCHours();
                var minutes = date.getUTCMinutes() < 10 ? '0'+date.getUTCMinutes() : date.getUTCMinutes();
                var seconds = date.getUTCSeconds() < 10 ? '0'+date.getUTCSeconds() : date.getUTCSeconds();
                el2.textContent = hours+':'+minutes+':'+seconds;
                fragment.appendChild(el2);

                var d1;
                var tick = tick_d.quote.replace(/\d$/,replace);
                var el3 = document.createElement('div');
                el3.classList.add('col');
                el3.innerHTML = tick;
                fragment.appendChild(el3);

                spots.appendChild(fragment);
                spots.scrollTop = spots.scrollHeight;

                if(d1 && duration===1){
                    var contract_status,
                        final_price,
                        pnl;

                    if  (  purchase_data.echo_req.passthrough.contract_type==="DIGITMATCH" && d1==purchase_data.echo_req.passthrough.barrier || purchase_data.echo_req.passthrough.contract_type==="DIGITDIFF" && d1!=purchase_data.echo_req.passthrough.barrier || purchase_data.echo_req.passthrough.contract_type==="DIGITEVEN" && d1%2===0 || purchase_data.echo_req.passthrough.contract_type==="DIGITODD" && d1%2 || purchase_data.echo_req.passthrough.contract_type==="DIGITOVER" && d1>purchase_data.echo_req.passthrough.barrier || purchase_data.echo_req.passthrough.contract_type==="DIGITUNDER" && d1<purchase_data.echo_req.passthrough.barrier){
                        spots.className = 'won';
                        final_price = $('#contract_purchase_payout p').text();
                        pnl = $('#contract_purchase_cost p').text();
                        contract_status = Content.localize().textContractStatusWon;
                    }
                    else{
                        spots.className = 'lost';
                        final_price = 0;
                        pnl = -$('#contract_purchase_cost p').text();
                        contract_status = Content.localize().textContractStatusLost;
                    }

                    updatePurchaseStatus(final_price, pnl, contract_status);
                }

                duration--;
                if(!duration){
                    purchase_data.echo_req.passthrough['duration'] = 0;
                }
            }

        }

    };

    return {
        display: display,
        update_spot_list: update_spot_list
    };

})();
<|endoftext|>


<commit_before>function(head, req) {
  var ddoc = this,
      templates = {},
      Handlebars = require("lib/handlebars"),
      array_replace_recursive = require("lib/array_replace_recursive").array_replace_recursive,
      dateToArray = require("lib/dateToArray").dateToArray,
      row,
      url;

  if (!req.query && !req.query.include_docs) {
    send('Please add include_docs to make this thing work');
  }

  provides('html',
    function() {
      var page = {items:[],copyright:'BigBlueHat'},
          posts = [],
          navigation = [],
          is_post = false;
      while(row = getRow()) {
        var last = row.key.pop(),
            is_collection = false,
            is_post = false;
        if (last == '_collection') {
          is_collection = true;
          last = row.key.pop();
        } else if (last == 'post') {
          is_post = true;
          last = row.key.pop();
        }
        var secondtolast = row.key.pop();
        // dump the extra dividing ""; it's only there for visual parsing
        var _ = row.key.pop();
        // it's the page
        if (secondtolast == '_' && last == '_') {
          page.url = url = row.key.join('/');
          page.title = row.doc.title;
        } else if (secondtolast == '' && last == 'site') {
          page.site = row.doc;
        } else if (secondtolast == '' && last == 'sitemap') {
          page.sitemap = row.doc.urls;
        } else if (secondtolast == '' && last == 'template') {
          page.template = row.doc._id;
          templates = row.doc.templates;
        } else if (secondtolast == '' && last == 'template_override') {
          page.template = row.doc._id;
          templates = array_replace_recursive(templates, row.doc.templates);
        } else {
          var partial_names = Object.keys(templates.partials);
          for (var i = 0; i < partial_names.length; i++) {
            Handlebars.registerPartial(partial_names[i],
              templates.partials[partial_names[i]]);
          }

          // TODO: base template selection off type
          if (!page.items[secondtolast]) {
            page.items[secondtolast] = {'area':[]};
          }
          if (row.doc.type) {
            if (row.doc.type === 'navigation') {
              navigation.push(page.items[secondtolast].area[last] = row);
            } else {
              var doc = row.doc;
              doc.base_url = page.url;
              // display settings
              if (row.value.display_title === false) {
                doc.title = "";
              }
              if (is_collection) {
                // general collection info handling
                if (page.items[secondtolast].area[last] === undefined) {
                  page.items[secondtolast].area[last] = {'collection':row.value['_collection'],
                                                        'posts': []};
                }
              } else if (is_post) {
                var post_template = templates.types[row.doc.type][page.items[secondtolast].area[last].collection.template_type] || templates.types[row.doc.type];
                // collection item handling
                page.items[secondtolast].area[last].posts
                  .push({'item':Handlebars.compile(post_template)(doc),
                         'published_date': dateToArray(row.value.published_date, 3).join('/')});
              } else {
                // non-post item
                var item_template = templates.types[row.doc.type]['default'] || templates.types[row.doc.type];
                page.items[secondtolast].area[last] = {'item':Handlebars.compile(item_template)(doc)};
              }
            }
          }
          // TODO: fix .first assignment
          if (secondtolast === 0) {
            page.items[secondtolast].classes = ['first'];
          }
        }
        is_post = false;
      } // end while

      // find navigation items and generate their content
      page.items.forEach(function(area, area_idx) {
        area.area.forEach(function(item, idx) {
          if (item.doc && item.doc.type && item.doc.type == 'navigation') {
            var nav_item = item,
                nav = {'sitemap':{}};

            if (nav_item.doc.show_only && nav_item.doc.show_only == 'children') {
              // TODO: this needs to be recursive
              page.sitemap.forEach(function(el) {
                if (el.body.url == nav_item.doc.current_url && el.children) {
                  navigation.sitemap = el.children;
                }
              });
            } else {
              navigation.sitemap = page.sitemap;
            }

            page.items[area_idx].area[idx] = {'item':Handlebars.compile(templates.types['navigation'])(navigation)};
          }
        });
      });
      page.site.host = req.headers.Host;
      //page.req = JSON.stringify(req);
      if (req.userCtx.name !== null) {
        // someone is logged in
        // TODO: (re)think through user object stuff
        page.user = {
          username: req.userCtx.name,
          roles: req.userCtx.roles
        };
      } else {
        // anonymous site visitor
        page.user = false;
      }
      send(Handlebars.compile(templates.page)(page));
    }
  );
}
<commit_msg>Handle display_title on page<commit_after>function(head, req) {
  var ddoc = this,
      templates = {},
      Handlebars = require("lib/handlebars"),
      array_replace_recursive = require("lib/array_replace_recursive").array_replace_recursive,
      dateToArray = require("lib/dateToArray").dateToArray,
      row,
      url;

  if (!req.query && !req.query.include_docs) {
    send('Please add include_docs to make this thing work');
  }

  provides('html',
    function() {
      var page = {items:[],copyright:'BigBlueHat'},
          posts = [],
          navigation = [],
          is_post = false;
      while(row = getRow()) {
        var last = row.key.pop(),
            is_collection = false,
            is_post = false;
        if (last == '_collection') {
          is_collection = true;
          last = row.key.pop();
        } else if (last == 'post') {
          is_post = true;
          last = row.key.pop();
        }
        var secondtolast = row.key.pop();
        // dump the extra dividing ""; it's only there for visual parsing
        var _ = row.key.pop();
        // it's the page
        if (secondtolast == '_' && last == '_') {
          page.url = url = row.key.join('/');
          if (row.doc.display_title !== false) {
            page.title = row.doc.title;
          }
        } else if (secondtolast == '' && last == 'site') {
          page.site = row.doc;
        } else if (secondtolast == '' && last == 'sitemap') {
          page.sitemap = row.doc.urls;
        } else if (secondtolast == '' && last == 'template') {
          page.template = row.doc._id;
          templates = row.doc.templates;
        } else if (secondtolast == '' && last == 'template_override') {
          page.template = row.doc._id;
          templates = array_replace_recursive(templates, row.doc.templates);
        } else {
          var partial_names = Object.keys(templates.partials);
          for (var i = 0; i < partial_names.length; i++) {
            Handlebars.registerPartial(partial_names[i],
              templates.partials[partial_names[i]]);
          }

          // TODO: base template selection off type
          if (!page.items[secondtolast]) {
            page.items[secondtolast] = {'area':[]};
          }
          if (row.doc.type) {
            if (row.doc.type === 'navigation') {
              navigation.push(page.items[secondtolast].area[last] = row);
            } else {
              var doc = row.doc;
              doc.base_url = page.url;
              // display settings
              if (row.value.display_title === false) {
                doc.title = "";
              }
              if (is_collection) {
                // general collection info handling
                if (page.items[secondtolast].area[last] === undefined) {
                  page.items[secondtolast].area[last] = {'collection':row.value['_collection'],
                                                        'posts': []};
                }
              } else if (is_post) {
                var post_template = templates.types[row.doc.type][page.items[secondtolast].area[last].collection.template_type] || templates.types[row.doc.type];
                // collection item handling
                page.items[secondtolast].area[last].posts
                  .push({'item':Handlebars.compile(post_template)(doc),
                         'published_date': dateToArray(row.value.published_date, 3).join('/')});
              } else {
                // non-post item
                var item_template = templates.types[row.doc.type]['default'] || templates.types[row.doc.type];
                page.items[secondtolast].area[last] = {'item':Handlebars.compile(item_template)(doc)};
              }
            }
          }
          // TODO: fix .first assignment
          if (secondtolast === 0) {
            page.items[secondtolast].classes = ['first'];
          }
        }
        is_post = false;
      } // end while

      // find navigation items and generate their content
      page.items.forEach(function(area, area_idx) {
        area.area.forEach(function(item, idx) {
          if (item.doc && item.doc.type && item.doc.type == 'navigation') {
            var nav_item = item,
                nav = {'sitemap':{}};

            if (nav_item.doc.show_only && nav_item.doc.show_only == 'children') {
              // TODO: this needs to be recursive
              page.sitemap.forEach(function(el) {
                if (el.body.url == nav_item.doc.current_url && el.children) {
                  navigation.sitemap = el.children;
                }
              });
            } else {
              navigation.sitemap = page.sitemap;
            }

            page.items[area_idx].area[idx] = {'item':Handlebars.compile(templates.types['navigation'])(navigation)};
          }
        });
      });
      page.site.host = req.headers.Host;
      //page.req = JSON.stringify(req);
      if (req.userCtx.name !== null) {
        // someone is logged in
        // TODO: (re)think through user object stuff
        page.user = {
          username: req.userCtx.name,
          roles: req.userCtx.roles
        };
      } else {
        // anonymous site visitor
        page.user = false;
      }
      send(Handlebars.compile(templates.page)(page));
    }
  );
}
<|endoftext|>


<commit_before>Kwf.onContentReady(function(readyEl) {
    var els = document.getElementsByTagName('a');
    for (var i=0; i<els.length; i++) {
        if (els[i].kwfLightbox) continue;
        var m = els[i].rel.match(/(^lightbox| lightbox)({.*?})?/);
        if (m) {
            var options = {};
            if (m[2]) options = Ext.decode(m[2]);
            var l;
            if (Kwf.EyeCandy.Lightbox.allByUrl[els[i].href]) {
                l = Kwf.EyeCandy.Lightbox.allByUrl[els[i].href];
            } else {
                l = new Kwf.EyeCandy.Lightbox.Lightbox(Ext.get(els[i]).dom.href, options);
            }
            els[i].kwfLightbox = l;
            Ext.EventManager.addListener(els[i], 'click', function(ev) {
                this.kwfLightbox.show({
                    clickTarget: Ext.get(this)
                });
                Kwf.Utils.HistoryState.currentState.lightbox = this.href;
                Kwf.Utils.HistoryState.pushState(document.title, this.href);
                ev.stopEvent();
            }, els[i], { stopEvent: true });
        }
    }

    Ext.query('.kwfLightbox').each(function(el) {
        if (el.kwfLightbox) return;
        var lightboxEl = Ext.get(el);
        var options = Ext.decode(lightboxEl.child('input.options').dom.value);
        var l = new Kwf.EyeCandy.Lightbox.Lightbox(window.location.href, options);
        Kwf.Utils.HistoryState.currentState.lightbox = window.location.href;
        Kwf.Utils.HistoryState.updateState();
        lightboxEl.enableDisplayMode('block');
        l.lightboxEl = lightboxEl;
        l.innerLightboxEl = lightboxEl.down('.kwfLightboxInner');
        l.fetched = true;
        l.initialize();
        l.closeHref = window.location.href.substr(0, window.location.href.lastIndexOf('/'));
        l.contentEl = l.innerLightboxEl.down('.kwfLightboxContent');
        l.style.afterCreateLightboxEl();
        l.style.onShow();
        l.style.onContentReady();
        el.kwfLightbox = l;
        Kwf.EyeCandy.Lightbox.currentOpen = l;
    });

    readyEl = Ext.get(readyEl);
    if (readyEl.isVisible() && Kwf.EyeCandy.Lightbox.currentOpen) {
        if (Kwf.EyeCandy.Lightbox.currentOpen.lightboxEl
            && Kwf.EyeCandy.Lightbox.currentOpen.lightboxEl.isVisible()
            && (Kwf.EyeCandy.Lightbox.currentOpen.innerLightboxEl.contains(readyEl)
            || readyEl.contains(Kwf.EyeCandy.Lightbox.currentOpen.innerLightboxEl))
        ) {
            Kwf.EyeCandy.Lightbox.currentOpen.style.onContentReady();
        }
    }
});

Kwf.Utils.HistoryState.on('popstate', function() {
    var lightbox = Kwf.Utils.HistoryState.currentState.lightbox;
    if (lightbox) {
        if (!Kwf.EyeCandy.Lightbox.allByUrl[lightbox]) return;
        if (Kwf.EyeCandy.Lightbox.currentOpen != Kwf.EyeCandy.Lightbox.allByUrl[lightbox]) {
            Kwf.EyeCandy.Lightbox.allByUrl[lightbox].show();
        }
    } else {
        if (Kwf.EyeCandy.Lightbox.currentOpen) {
            Kwf.EyeCandy.Lightbox.currentOpen.close();
        }
    }
});

Ext.ns('Kwf.EyeCandy.Lightbox');
Kwf.EyeCandy.Lightbox.currentOpen = null;
Kwf.EyeCandy.Lightbox.allByUrl = {};
Kwf.EyeCandy.Lightbox.Lightbox = function(href, options) {
    this.href = href;
    Kwf.EyeCandy.Lightbox.allByUrl[href] = this;
    this.options = options;
    if (options.style) {
        this.style = new Kwf.EyeCandy.Lightbox.Styles[options.style](this);
    } else {
        this.style = new Kwf.EyeCandy.Lightbox.Styles.CenterBox(this);
    }
};
Kwf.EyeCandy.Lightbox.Lightbox.prototype = {
    fetched: false,
    _blockOnContentReady: false,
    createLightboxEl: function()
    {
        if (this.lightboxEl) return;

        var lightbox = Ext.getBody().createChild({
            cls: 'kwfLightbox' + (this.options.style ? ' kwfLightbox'+this.options.style : ''),
            html: '

'
        });
        lightbox.dom.kwfLightbox = this; //don't initialize again in onContentReady
        lightbox.enableDisplayMode('block');
        this.lightboxEl = lightbox;
        this.innerLightboxEl = lightbox.down('.kwfLightboxInner');

        var el = this.innerLightboxEl;

        if (this.options.width) {
            el.setWidth(parseInt(this.options.width) + el.getBorderWidth("lr") + el.getPadding("lr"));
        }
        if (this.options.height) {
            el.setHeight(parseInt(this.options.height) + el.getBorderWidth("tb") + el.getPadding("tb"));
        }
        this.style.afterCreateLightboxEl();
        this.lightboxEl.hide();
    },
    fetchContent: function()
    {
        if (this.fetched) return;
        this.fetched = true;

        var url = '/kwf/util/kwc/render';
        if (Kwf.Debug.rootFilename) url = Kwf.Debug.rootFilename + url;
        Ext.Ajax.request({
            params: { url: this.href },
            url: url,
            success: function(response, options) {
                this.contentEl = this.innerLightboxEl.createChild({
                    cls: 'kwfLightboxContent'
                });
                this.closeButtonEl = this.innerLightboxEl.createChild({
                    cls: 'closeButton',
                    tag: 'a',
                    href: '#'
                });

                this.style.updateContent(response.responseText);

                if (this.lightboxEl.isVisible()) this.contentEl.hide();

                var showContent = function() {
                    this.innerLightboxEl.removeClass('kwfLightboxLoading');
                    this.innerLightboxEl.child('.loading').remove();
                    if (this.lightboxEl.isVisible()) {
                        this.contentEl.fadeIn();
                    }
                    this._blockOnContentReady = true; //don't resize twice
                    Kwf.callOnContentReady(this.contentEl.dom, {newRender: true});
                    this._blockOnContentReady = false;
                    this.style.afterContentShown();
                    if (this.lightboxEl.isVisible()) {
                        this.preloadLinks();
                    }
                };
                var imagesToLoad = 0;
                this.contentEl.query('img.hideWhileLoading').each(function(imgEl) {
                    imagesToLoad++;
                    imgEl.onload = (function() {
                        imagesToLoad--;
                        if (imagesToLoad <= 0) showContent.call(this);
                    }).createDelegate(this);
                }, this);
                if (imagesToLoad == 0) showContent.call(this);
                this.initialize();
            },
            failure: function() {
                //fallback
                location.href = this.href;
            },
            scope: this
        });
    },
    show: function(options)
    {
        this.createLightboxEl();
        this.style.onShow(options);

        if (!this.closeHref) {
            if (Kwf.EyeCandy.Lightbox.currentOpen) {
                this.closeHref = Kwf.EyeCandy.Lightbox.currentOpen.closeHref;
            } else {
                this.closeHref = window.location.href;
            }
        }
        if (Kwf.EyeCandy.Lightbox.currentOpen) {
            var closeOptions = {};
            if (options.clickTarget) closeOptions.showClickTarget = options.clickTarget;
            Kwf.EyeCandy.Lightbox.currentOpen.close(closeOptions);
        }
        Kwf.EyeCandy.Lightbox.currentOpen = this;

        this.lightboxEl.addClass('kwfLightboxOpen');
        if (this.fetched) {
            if (!this.lightboxEl.isVisible()) {
                this.lightboxEl.fadeIn();
                this.preloadLinks();
                Kwf.callOnContentReady(this.innerLightboxEl.dom, {newRender: false});
            }
            this.style.afterContentShown();
        } else {
            this.lightboxEl.show();
            this.fetchContent();
        }
        this.style.afterShow(options);
        Kwf.Statistics.count(this.href);
    },
    close: function(options) {
        this.lightboxEl.hide();
        //so eg. flash component can remove object
        Kwf.callOnContentReady(this.lightboxEl, {newRender: false});
        this.lightboxEl.show();

        this.style.onClose(options);
        this.lightboxEl.removeClass('kwfLightboxOpen');
        Kwf.EyeCandy.Lightbox.currentOpen = null;
    },
    closeAndPushState: function() {
        delete Kwf.Utils.HistoryState.currentState.lightbox;
        Kwf.Utils.HistoryState.pushState(document.title, this.closeHref);
        this.close();
    },
    initialize: function()
    {
        var closeButtons = this.innerLightboxEl.select('.closeButton');
        closeButtons.each(function(el) {
            el.on('click', function(ev) {
                this.closeAndPushState();
                ev.stopEvent();
            }, this);
        }, this);
    },
    preloadLinks: function() {
        this.innerLightboxEl.query('a.preload').each(function(el) {
            if (el.kwfLightbox) el.kwfLightbox.preload();
        }, this);
    },
    preload: function() {
        this.createLightboxEl();
        this.fetchContent();
    }
};

Kwf.EyeCandy.Lightbox.Styles = {};
Kwf.EyeCandy.Lightbox.Styles.Abstract = function(lightbox) {
    this.lightbox = lightbox;
};
Kwf.EyeCandy.Lightbox.Styles.Abstract.masks = 0;
Kwf.EyeCandy.Lightbox.Styles.Abstract.prototype = {
    afterCreateLightboxEl: Ext.emptyFn,
    afterContentShown: Ext.emptyFn,
    updateContent: function(responseText) {
        this.lightbox.contentEl.update(responseText);
    },
    onShow: Ext.emptyFn,
    afterShow: Ext.emptyFn,
    onClose: Ext.emptyFn,
    afterClose: Ext.emptyFn,
    onContentReady: Ext.emptyFn,

    mask: function() {
        //calling mask multiple times in valid, unmask must be called exactly often
        Kwf.EyeCandy.Lightbox.Styles.Abstract.masks++;
        if (Kwf.EyeCandy.Lightbox.Styles.Abstract.masks > 1) return;
        Ext.getBody().addClass('kwfLightboxTheaterMode');
        var maskEl = Ext.getBody().mask();
        Ext.getBody().removeClass('x-masked');
        Ext.getBody().removeClass('x-masked-relative');
        maskEl.addClass('lightboxMask');
        maskEl.dom.style.height = '';
        maskEl.dom.style.width = '';

        //maskEl.setHeight(Math.max(Ext.lib.Dom.getViewHeight(), Ext.lib.Dom.getDocumentHeight()));

        maskEl.on('click', function() {
            this.lightbox.closeAndPushState();
        }, this);
    },
    unmask: function() {
        Kwf.EyeCandy.Lightbox.Styles.Abstract.masks--;
        if (Kwf.EyeCandy.Lightbox.Styles.Abstract.masks > 0) return;
        Ext.getBody()._mask.fadeOut({
            concurrent: true,
            callback: function() {
                Ext.getBody().removeClass('kwfLightboxTheaterMode');
                Ext.getBody()._mask.remove();
            },
            scope: this
        });
    }
};

Kwf.EyeCandy.Lightbox.Styles.CenterBox = Ext.extend(Kwf.EyeCandy.Lightbox.Styles.Abstract, {
    afterCreateLightboxEl: function() {
        this.lightbox.lightboxEl.on('click', function(ev) {
            if (ev.getTarget() == this.lightbox.lightboxEl.dom) {
                this.lightbox.closeAndPushState();
            }
        }, this);
        this._center();
    },
    afterContentShown: function() {
        this._center();
    },
    updateContent: function(responseText) {
        var isVisible = this.lightbox.lightboxEl.isVisible();

        this.lightbox.lightboxEl.show(); //to mesaure

        var originalSize = this.lightbox.innerLightboxEl.getSize();

        Kwf.EyeCandy.Lightbox.Styles.CenterBox.superclass.updateContent.apply(this, arguments);

        if (!this.lightbox.options.height) this.lightbox.innerLightboxEl.dom.style.height = '';
        if (!this.lightbox.options.width) this.lightbox.innerLightboxEl.dom.style.width = '';
        var newSize = this.lightbox.contentEl.getSize();
        newSize['height'] += this.lightbox.innerLightboxEl.getBorderWidth("tb")+this.lightbox.innerLightboxEl.getPadding("tb");
        newSize['width'] += this.lightbox.innerLightboxEl.getBorderWidth("lr")+this.lightbox.innerLightboxEl.getPadding("lr");

        if (isVisible) {
            this.lightbox.innerLightboxEl.setSize(newSize);
            if (this.lightbox.innerLightboxEl.getColor('backgroundColor')) {
                //animate size only if backgroundColor is set - else it doesn't make sense
                this._center(true);
                this.lightbox.innerLightboxEl.setSize(originalSize);
                this.lightbox.innerLightboxEl.setSize(newSize, null, true);
            } else {
                this._center(false);
            }
        } else {
            this.lightbox.innerLightboxEl.setSize(newSize);
            this._center(false);
            this.lightbox.lightboxEl.hide();
        }
    },
    onShow: function() {
        this.mask();
    },
    onClose: function(options) {
        this.lightbox.lightboxEl.fadeOut({
            concurrent: true,
            callback: function() {
                this.afterClose();
            },
            scope: this
        });
        this.unmask();
    },
    _getCenterXy: function() {
        var xy = this.lightbox.innerLightboxEl.getAlignToXY(document, 'c-c');

        //if lightbox is larget than viewport don't position lightbox above, the user can only scroll down
        if (xy[0] < Ext.getBody().getScroll().left+20) xy[0] = Ext.getBody().getScroll().left+20;
        if (xy[1] < Ext.getBody().getScroll().top+20) xy[1] = Ext.getBody().getScroll().top+20;

        return xy;
    },
    _center: function(anim) {
        if (!this.lightbox.lightboxEl.isVisible(true)) return;
        this.lightbox.innerLightboxEl.setStyle({ top: 0, left: 0 });
        this.lightbox.innerLightboxEl.setXY(this._getCenterXy(), anim);
    },

    onContentReady: function()
    {
        if (this.lightbox._blockOnContentReady) return;
        if (!this.lightbox.contentEl) return;

        //adjust size if height changed
        var newSize = this.lightbox.contentEl.getSize();
        newSize['height'] += this.lightbox.innerLightboxEl.getBorderWidth("tb")+this.lightbox.innerLightboxEl.getPadding("tb");
        newSize['width'] += this.lightbox.innerLightboxEl.getBorderWidth("lr")+this.lightbox.innerLightboxEl.getPadding("lr");
        if (this.lightbox.contentEl.child('> .kwfRoundBorderBox > .kwfMiddleCenter')) {
            newSize['height'] -= this.lightbox.contentEl.child('> .kwfRoundBorderBox > .kwfMiddleCenter').getPadding('tb');
        }
        var originalSize = this.lightbox.innerLightboxEl.getSize();
        this.lightbox.innerLightboxEl.setSize(newSize); //set to new size so centering works (no animation)
        var centerXy = this._getCenterXy();
        var xy = this.lightbox.innerLightboxEl.getXY();
        xy[0] = centerXy[0];
        if (centerXy[1] < xy[1]) xy[1] = centerXy[1]; //move up, but not down
        this.lightbox.innerLightboxEl.setXY(xy, true);
        this.lightbox.innerLightboxEl.setSize(originalSize); //set back to previous size for animation
        this.lightbox.innerLightboxEl.setSize(newSize, null, true); //now animate to new size
    }
});
<commit_msg>disable animation when re-opening lightbox<commit_after>Kwf.onContentReady(function(readyEl) {
    var els = document.getElementsByTagName('a');
    for (var i=0; i<els.length; i++) {
        if (els[i].kwfLightbox) continue;
        var m = els[i].rel.match(/(^lightbox| lightbox)({.*?})?/);
        if (m) {
            var options = {};
            if (m[2]) options = Ext.decode(m[2]);
            var l;
            if (Kwf.EyeCandy.Lightbox.allByUrl[els[i].href]) {
                l = Kwf.EyeCandy.Lightbox.allByUrl[els[i].href];
            } else {
                l = new Kwf.EyeCandy.Lightbox.Lightbox(Ext.get(els[i]).dom.href, options);
            }
            els[i].kwfLightbox = l;
            Ext.EventManager.addListener(els[i], 'click', function(ev) {
                this.kwfLightbox.show({
                    clickTarget: Ext.get(this)
                });
                Kwf.Utils.HistoryState.currentState.lightbox = this.href;
                Kwf.Utils.HistoryState.pushState(document.title, this.href);
                ev.stopEvent();
            }, els[i], { stopEvent: true });
        }
    }

    Ext.query('.kwfLightbox').each(function(el) {
        if (el.kwfLightbox) return;
        var lightboxEl = Ext.get(el);
        var options = Ext.decode(lightboxEl.child('input.options').dom.value);
        var l = new Kwf.EyeCandy.Lightbox.Lightbox(window.location.href, options);
        Kwf.Utils.HistoryState.currentState.lightbox = window.location.href;
        Kwf.Utils.HistoryState.updateState();
        lightboxEl.enableDisplayMode('block');
        l.lightboxEl = lightboxEl;
        l.innerLightboxEl = lightboxEl.down('.kwfLightboxInner');
        l.fetched = true;
        l.initialize();
        l.closeHref = window.location.href.substr(0, window.location.href.lastIndexOf('/'));
        l.contentEl = l.innerLightboxEl.down('.kwfLightboxContent');
        l.style.afterCreateLightboxEl();
        l.style.onShow();
        l.style.onContentReady();
        el.kwfLightbox = l;
        Kwf.EyeCandy.Lightbox.currentOpen = l;
    });

    readyEl = Ext.get(readyEl);
    if (readyEl.isVisible() && Kwf.EyeCandy.Lightbox.currentOpen) {
        if (Kwf.EyeCandy.Lightbox.currentOpen.lightboxEl
            && Kwf.EyeCandy.Lightbox.currentOpen.lightboxEl.isVisible()
            && (Kwf.EyeCandy.Lightbox.currentOpen.innerLightboxEl.contains(readyEl)
            || readyEl.contains(Kwf.EyeCandy.Lightbox.currentOpen.innerLightboxEl))
        ) {
            Kwf.EyeCandy.Lightbox.currentOpen.style.onContentReady();
        }
    }
});

Kwf.Utils.HistoryState.on('popstate', function() {
    var lightbox = Kwf.Utils.HistoryState.currentState.lightbox;
    if (lightbox) {
        if (!Kwf.EyeCandy.Lightbox.allByUrl[lightbox]) return;
        if (Kwf.EyeCandy.Lightbox.currentOpen != Kwf.EyeCandy.Lightbox.allByUrl[lightbox]) {
            Kwf.EyeCandy.Lightbox.allByUrl[lightbox].show();
        }
    } else {
        if (Kwf.EyeCandy.Lightbox.currentOpen) {
            Kwf.EyeCandy.Lightbox.currentOpen.close();
        }
    }
});

Ext.ns('Kwf.EyeCandy.Lightbox');
Kwf.EyeCandy.Lightbox.currentOpen = null;
Kwf.EyeCandy.Lightbox.allByUrl = {};
Kwf.EyeCandy.Lightbox.Lightbox = function(href, options) {
    this.href = href;
    Kwf.EyeCandy.Lightbox.allByUrl[href] = this;
    this.options = options;
    if (options.style) {
        this.style = new Kwf.EyeCandy.Lightbox.Styles[options.style](this);
    } else {
        this.style = new Kwf.EyeCandy.Lightbox.Styles.CenterBox(this);
    }
};
Kwf.EyeCandy.Lightbox.Lightbox.prototype = {
    fetched: false,
    _blockOnContentReady: false,
    createLightboxEl: function()
    {
        if (this.lightboxEl) return;

        var lightbox = Ext.getBody().createChild({
            cls: 'kwfLightbox' + (this.options.style ? ' kwfLightbox'+this.options.style : ''),
            html: '

'
        });
        lightbox.dom.kwfLightbox = this; //don't initialize again in onContentReady
        lightbox.enableDisplayMode('block');
        this.lightboxEl = lightbox;
        this.innerLightboxEl = lightbox.down('.kwfLightboxInner');

        var el = this.innerLightboxEl;

        if (this.options.width) {
            el.setWidth(parseInt(this.options.width) + el.getBorderWidth("lr") + el.getPadding("lr"));
        }
        if (this.options.height) {
            el.setHeight(parseInt(this.options.height) + el.getBorderWidth("tb") + el.getPadding("tb"));
        }
        this.style.afterCreateLightboxEl();
        this.lightboxEl.hide();
    },
    fetchContent: function()
    {
        if (this.fetched) return;
        this.fetched = true;

        var url = '/kwf/util/kwc/render';
        if (Kwf.Debug.rootFilename) url = Kwf.Debug.rootFilename + url;
        Ext.Ajax.request({
            params: { url: this.href },
            url: url,
            success: function(response, options) {
                this.contentEl = this.innerLightboxEl.createChild({
                    cls: 'kwfLightboxContent'
                });
                this.closeButtonEl = this.innerLightboxEl.createChild({
                    cls: 'closeButton',
                    tag: 'a',
                    href: '#'
                });

                this.style.updateContent(response.responseText);

                if (this.lightboxEl.isVisible()) this.contentEl.hide();

                var showContent = function() {
                    this.innerLightboxEl.removeClass('kwfLightboxLoading');
                    this.innerLightboxEl.child('.loading').remove();
                    if (this.lightboxEl.isVisible()) {
                        this.contentEl.fadeIn();
                    }
                    this._blockOnContentReady = true; //don't resize twice
                    Kwf.callOnContentReady(this.contentEl.dom, {newRender: true});
                    this._blockOnContentReady = false;
                    this.style.afterContentShown();
                    if (this.lightboxEl.isVisible()) {
                        this.preloadLinks();
                    }
                };
                var imagesToLoad = 0;
                this.contentEl.query('img.hideWhileLoading').each(function(imgEl) {
                    imagesToLoad++;
                    imgEl.onload = (function() {
                        imagesToLoad--;
                        if (imagesToLoad <= 0) showContent.call(this);
                    }).createDelegate(this);
                }, this);
                if (imagesToLoad == 0) showContent.call(this);
                this.initialize();
            },
            failure: function() {
                //fallback
                location.href = this.href;
            },
            scope: this
        });
    },
    show: function(options)
    {
        this.createLightboxEl();
        this.style.onShow(options);

        if (!this.closeHref) {
            if (Kwf.EyeCandy.Lightbox.currentOpen) {
                this.closeHref = Kwf.EyeCandy.Lightbox.currentOpen.closeHref;
            } else {
                this.closeHref = window.location.href;
            }
        }
        if (Kwf.EyeCandy.Lightbox.currentOpen) {
            var closeOptions = {};
            if (options.clickTarget) closeOptions.showClickTarget = options.clickTarget;
            Kwf.EyeCandy.Lightbox.currentOpen.close(closeOptions);
        }
        Kwf.EyeCandy.Lightbox.currentOpen = this;

        this.lightboxEl.addClass('kwfLightboxOpen');
        if (this.fetched) {
            if (!this.lightboxEl.isVisible()) {
                this.lightboxEl.fadeIn();
                this.preloadLinks();
                Kwf.callOnContentReady(this.innerLightboxEl.dom, {newRender: false});
            }
            this.style.afterContentShown();
        } else {
            this.lightboxEl.show();
            this.fetchContent();
        }
        this.style.afterShow(options);
        Kwf.Statistics.count(this.href);
    },
    close: function(options) {
        this.lightboxEl.hide();
        //so eg. flash component can remove object
        Kwf.callOnContentReady(this.lightboxEl, {newRender: false});
        this.lightboxEl.show();

        this.style.onClose(options);
        this.lightboxEl.removeClass('kwfLightboxOpen');
        Kwf.EyeCandy.Lightbox.currentOpen = null;
    },
    closeAndPushState: function() {
        delete Kwf.Utils.HistoryState.currentState.lightbox;
        Kwf.Utils.HistoryState.pushState(document.title, this.closeHref);
        this.close();
    },
    initialize: function()
    {
        var closeButtons = this.innerLightboxEl.select('.closeButton');
        closeButtons.each(function(el) {
            el.on('click', function(ev) {
                this.closeAndPushState();
                ev.stopEvent();
            }, this);
        }, this);
    },
    preloadLinks: function() {
        this.innerLightboxEl.query('a.preload').each(function(el) {
            if (el.kwfLightbox) el.kwfLightbox.preload();
        }, this);
    },
    preload: function() {
        this.createLightboxEl();
        this.fetchContent();
    }
};

Kwf.EyeCandy.Lightbox.Styles = {};
Kwf.EyeCandy.Lightbox.Styles.Abstract = function(lightbox) {
    this.lightbox = lightbox;
};
Kwf.EyeCandy.Lightbox.Styles.Abstract.masks = 0;
Kwf.EyeCandy.Lightbox.Styles.Abstract.prototype = {
    afterCreateLightboxEl: Ext.emptyFn,
    afterContentShown: Ext.emptyFn,
    updateContent: function(responseText) {
        this.lightbox.contentEl.update(responseText);
    },
    onShow: Ext.emptyFn,
    afterShow: Ext.emptyFn,
    onClose: Ext.emptyFn,
    afterClose: Ext.emptyFn,
    onContentReady: Ext.emptyFn,

    mask: function() {
        //calling mask multiple times in valid, unmask must be called exactly often
        Kwf.EyeCandy.Lightbox.Styles.Abstract.masks++;
        if (Kwf.EyeCandy.Lightbox.Styles.Abstract.masks > 1) return;
        Ext.getBody().addClass('kwfLightboxTheaterMode');
        var maskEl = Ext.getBody().mask();
        Ext.getBody().removeClass('x-masked');
        Ext.getBody().removeClass('x-masked-relative');
        maskEl.addClass('lightboxMask');
        maskEl.dom.style.height = '';
        maskEl.dom.style.width = '';

        //maskEl.setHeight(Math.max(Ext.lib.Dom.getViewHeight(), Ext.lib.Dom.getDocumentHeight()));

        maskEl.on('click', function() {
            this.lightbox.closeAndPushState();
        }, this);
    },
    unmask: function() {
        Kwf.EyeCandy.Lightbox.Styles.Abstract.masks--;
        if (Kwf.EyeCandy.Lightbox.Styles.Abstract.masks > 0) return;
        Ext.getBody()._mask.fadeOut({
            concurrent: true,
            callback: function() {
                Ext.getBody().removeClass('kwfLightboxTheaterMode');
                Ext.getBody()._mask.remove();
            },
            scope: this
        });
    }
};

Kwf.EyeCandy.Lightbox.Styles.CenterBox = Ext.extend(Kwf.EyeCandy.Lightbox.Styles.Abstract, {
    afterCreateLightboxEl: function() {
        this.lightbox.lightboxEl.on('click', function(ev) {
            if (ev.getTarget() == this.lightbox.lightboxEl.dom) {
                this.lightbox.closeAndPushState();
            }
        }, this);
        this._center();
    },
    afterContentShown: function() {
        this._center();
    },
    updateContent: function(responseText) {
        var isVisible = this.lightbox.lightboxEl.isVisible();

        this.lightbox.lightboxEl.show(); //to mesaure

        var originalSize = this.lightbox.innerLightboxEl.getSize();

        Kwf.EyeCandy.Lightbox.Styles.CenterBox.superclass.updateContent.apply(this, arguments);

        if (!this.lightbox.options.height) this.lightbox.innerLightboxEl.dom.style.height = '';
        if (!this.lightbox.options.width) this.lightbox.innerLightboxEl.dom.style.width = '';
        var newSize = this.lightbox.contentEl.getSize();
        newSize['height'] += this.lightbox.innerLightboxEl.getBorderWidth("tb")+this.lightbox.innerLightboxEl.getPadding("tb");
        newSize['width'] += this.lightbox.innerLightboxEl.getBorderWidth("lr")+this.lightbox.innerLightboxEl.getPadding("lr");

        if (isVisible) {
            this.lightbox.innerLightboxEl.setSize(newSize);
            if (this.lightbox.innerLightboxEl.getColor('backgroundColor')) {
                //animate size only if backgroundColor is set - else it doesn't make sense
                this._center(true);
                this.lightbox.innerLightboxEl.setSize(originalSize);
                this.lightbox.innerLightboxEl.setSize(newSize, null, true);
            } else {
                this._center(false);
            }
        } else {
            this.lightbox.innerLightboxEl.setSize(newSize);
            this._center(false);
            this.lightbox.lightboxEl.hide();
        }
    },
    onShow: function() {
        this.mask();
    },
    onClose: function(options) {
        this.lightbox.lightboxEl.fadeOut({
            concurrent: true,
            callback: function() {
                this.afterClose();
            },
            scope: this
        });
        this.unmask();
    },
    _getCenterXy: function() {
        var xy = this.lightbox.innerLightboxEl.getAlignToXY(document, 'c-c');

        //if lightbox is larget than viewport don't position lightbox above, the user can only scroll down
        if (xy[0] < Ext.getBody().getScroll().left+20) xy[0] = Ext.getBody().getScroll().left+20;
        if (xy[1] < Ext.getBody().getScroll().top+20) xy[1] = Ext.getBody().getScroll().top+20;

        return xy;
    },
    _center: function(anim) {
        if (!this.lightbox.lightboxEl.isVisible(true)) return;
        this.lightbox.innerLightboxEl.setStyle({ top: 0, left: 0 });
        this.lightbox.innerLightboxEl.setXY(this._getCenterXy(), anim);
    },

    onContentReady: function()
    {
        if (this.lightbox._blockOnContentReady) return;
        if (!this.lightbox.contentEl) return;

        //adjust size if height changed
        var newSize = this.lightbox.contentEl.getSize();
        newSize['height'] += this.lightbox.innerLightboxEl.getBorderWidth("tb")+this.lightbox.innerLightboxEl.getPadding("tb");
        newSize['width'] += this.lightbox.innerLightboxEl.getBorderWidth("lr")+this.lightbox.innerLightboxEl.getPadding("lr");
        if (this.lightbox.contentEl.child('> .kwfRoundBorderBox > .kwfMiddleCenter')) {
            newSize['height'] -= this.lightbox.contentEl.child('> .kwfRoundBorderBox > .kwfMiddleCenter').getPadding('tb');
        }
        var originalSize = this.lightbox.innerLightboxEl.getSize();
        this.lightbox.innerLightboxEl.setSize(newSize); //set to new size so centering works (no animation)
        var centerXy = this._getCenterXy();
        var xy = this.lightbox.innerLightboxEl.getXY();
        xy[0] = centerXy[0];
        if (centerXy[1] < xy[1]) xy[1] = centerXy[1]; //move up, but not down
        /*
        //animation to new position disabled, buggy
        this.lightbox.innerLightboxEl.setXY(xy, true);
        this.lightbox.innerLightboxEl.setSize(originalSize); //set back to previous size for animation
        this.lightbox.innerLightboxEl.setSize(newSize, null, true); //now animate to new size
        */

        //instead center unanimated
        this.lightbox.innerLightboxEl.setXY(xy);
    }
});
<|endoftext|>