﻿// JScript File
Type.registerNamespace('ActiveBets');

var $wl = function(message) {
    //    var __log = document.getElementById('log');
    //    __log.innerHTML += String.format("{0}<br>", message);
    //    var __log = document.getElementById('log');
    //    __log.innerHTML += String.format("{0}<br>", message);
}

/*******************  ActiveBets.BettingsCard  ***********************/
$cleanBetSlip = function() {
    ActiveBets.ExtApp.get_bett_slip().delete_all();
}
$addBet = function(obj, eventId, eventDate, leagueId, homeTeamName, guestTeamName, oddId, betTypeCode, oddFactor, betGroupTypeId, betTypeId, columnIndex, oddKind, betTypeName, eventName, oddPoint, notes) {
    ActiveBets.ExtApp.get_bett_slip().add_to_card(new ActiveBets.Bet(null, eventId, eventDate, leagueId, homeTeamName, guestTeamName, oddId, betTypeCode, oddFactor, betGroupTypeId, betTypeId, true, 0.0, columnIndex, oddKind, betTypeName, eventName, oddPoint, notes, false));
}

$ShowLimits = function() {
    ActiveBets.ExtApp.get_bett_slip().show_limits();
}

$ShowBanks = function() {
    ActiveBets.ExtApp.get_bett_slip().show_banks();
}

ActiveBets.BettingsCard = function(element) {
    ActiveBets.BettingsCard.initializeBase(this, [element]);

    //#region [ Server Members ]
    this.InputCss = null;
    //	this.TemplateID = null;
    this.Items = {};
    this.Systems = {};

    //#region [ Private Members ]
    /* Collection of ActiveBets.Bet */
    this.collection = [];
    this._s_p_c = 0;
    this._b_p_c = 0;
    /* Collection of ActiveBets.SysBet */
    this.sys_collection = [];

    this.is_limits_visible = false;
    this.is_banks_visible = false;

    //#region [ UI ]
    //	this.Template = null;
    this._pages = [];
    this._sel_pageIdx = 0;
    this._timer = new Sys.Timer();

    this.Single = null;
    this._single_pane = null;
    this._multiple_pane = null;

    this._app_onload$delegate = Function.createDelegate(this, this._app_onload);
}
ActiveBets.BettingsCard.prototype = {

    initialize: function() {
        ActiveBets.BettingsCard.callBaseMethod(this, 'initialize');

        Array.add(this._pages, $get("bs_single"));
        Array.add(this._pages, $get("bs_confirm"));

        this.Single = new ActiveBets.Single(this, this.InputCss);
        Sys.Application.add_load(this._app_onload$delegate);
    },

    get_app: function() {
        return ActiveBets.App;
    },

    //#region [ pages ]
    get_pageIndex: function() {
        return this._sel_pageIdx;
    },
    pageIndex_change: function(/*int*/idx) {
        if ((this._sel_pageIdx != idx) && (idx > -1) && (idx < this._pages.length)) {
            this._pages[this._sel_pageIdx].style.display = "none";
            this._sel_pageIdx = idx;
            this._pages[this._sel_pageIdx].style.display = "";
        }
    },
    //#endregion [ pages ]

    dispose: function() {
        Sys.Application.remove_load(this._app_onload$delegate);
        ActiveBets.BettingsCard.callBaseMethod(this, 'dispose');
    },

    _app_onload: function() {
        Sys.Application.remove_load(this._app_onload$delegate);

        this.Single.set_owner(this);
        if (this.Items.length <= 0)
            return;

        this.initializeTimer();

        this._restore();
    },

    initializeTimer: function() {
        this._timer.set_interval(0);
        this._timer.add_tick(Function.createDelegate(this, this._recreate_confirm));
        this._timer.set_enabled(false);
    },

    _restore: function() {
        for (var index in this.Items) {
            if (this.Items[index].IsBank) {
                this.is_banks_visible = true;
                break;
            }
        }

        // Restore Bets (ActiveBets.Bet)
        for (var index in this.Items) {
            var sBet = this.Items[index];
            var oBet = new ActiveBets.Bet(sBet.Id, sBet.EventId, sBet.EventDate, sBet.LeagueId,
                sBet.HomeTeamName, sBet.GuestTeamName, sBet.OddId, sBet.BetTypeCode, sBet.OddFactor, sBet.BetGroupTypeId,
                sBet.BetTypeId, sBet.IsSystemPart, sBet.Amount, sBet.ColumnIndex, sBet.OddKind, sBet.BetTypeName,
                sBet.EventName, sBet.OddPoint, sBet.Notes, sBet.IsBank, sBet.EventCode);

            if (sBet.Limit != null)
                oBet.set_limits(sBet.Limit.MinPay, sBet.Limit.MaxPay);

            this.add_bet_inner(oBet);

            if (!oBet.check_limits()) {
                oBet.set_error(String.format('1. {0}', Res.LimitError));
            }
        }

        // Restore System including Combi Bets (ActiveBets.SSBet, ActiveBets.SCBet)
        for (var index in this.Systems) {
            var sBet = this.Systems[index];

            if (sBet.StakeType == ActiveBets.BetTypes.System) {
                var ssBet = new ActiveBets.SSBet(sBet.System, sBet.Amount);
                this.add_sysbet_inner(ssBet);
            }
            else if (sBet.StakeType == ActiveBets.BetTypes.Combi) {
                var ssBet = new ActiveBets.SCBet(sBet);
                this.add_sysbet_inner(ssBet);
            }
        }
        this.update_sys_limits();
        //        this.check_sys();
        this.update_card();
    },

    generateId: function() {
        var result, i, j;
        result = '';
        for (j = 0; j < 32; j++) {
            if (j == 8 || j == 12 || j == 16 || j == 20)
                result = result + '-';
            i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
            result = result + i;
        }
        return result
    },
    contais_by_id: function(id) {
        for (var idx in this.collection) {
            if (this.collection[idx].equals_by_id(id))
                return true;
        }
        return false;
    },

    // region [ add ]
    add_bet_inner: function(/* type = ActiveBets.Bet */oBet) {
        if (oBet.Id == null) {
            do {
                var id = this.generateId();
                if (!this.contais_by_id(id)) {
                    oBet.Id = id;
                    break;
                }
            } while (true)
        }
        Array.add(this.collection, oBet);
        this.Single.add_betrow(oBet);
        oBet.select_region(true);
        this.update_s_p_c();
        this.update_b_p_c();
    },

    add_sysbet_inner: function(sBet) {
        Array.add(this.sys_collection, sBet);
        if (sBet.BetType == ActiveBets.BetTypes.Combi)
            this.Single.add_combirow(sBet);
        else {
            var s = this.get_sys_parts_count();
            var b = this.get_banks_count();

            var index = 1;

            if (this.sys_collection != null && this.sys_collection.length > 1) {
                while (sBet.get_system() > this.sys_collection[index].get_system()) {
                    index++;
                }
            }

            this.Single.add_sysbetrow(sBet, index - 1);
        }
    },

    add_to_card: function(/*ActiveBets.Bet*/oBet) {
        var result = false;
        if (result = this.contains(oBet))
            this.remove_bet(null, this.get_bet(oBet));
        else if (this.get_bets_count() < ActiveBets.App.get_maxStakesCount()) {
            this.add_bet(oBet);
        }
        else {
            $get('ErrorText2').style.display = 'none';
            $get('ErrorText3').style.display = 'none';
            $get('ErrorText4').style.display = 'none';
            var anonymousUserPopup = $find('AnonymousUserPopup');
            $get('ErrorText1').style.display = '';
            anonymousUserPopup.show();
        }
        return result;
    },

    _recreate_confirm: function() {

        var bs_CDB = $get("bs_CDB", this.get_element());
        while (bs_CDB.rows.length > 0) {
            bs_CDB.deleteRow(0);
        }
        var is_sys = false;
        for (var idx in this.sys_collection) {
            var oSBet = this.sys_collection[idx];
            is_sys = oSBet.is_have_stake();
            if (is_sys)
                break;
        }

        for (var idx in this.collection) {
            var oBet = this.collection[idx];
            if ((is_sys && oBet.IsSystemPart) || oBet.is_have_stake()) {

                var tr = $common.createElementFromTemplate({ nodeName: "tr" }, bs_CDB)
                var td = $common.createElementFromTemplate({ nodeName: "td" }, tr);

                var table = $common.createElementFromTemplate({ nodeName: 'table',
                    properties: { className: 'tabBet' }
                }, td);
                var tbody = $common.createElementFromTemplate({ nodeName: "tbody" }, table);

                var tr0 = $common.createElementFromTemplate({ nodeName: "tr" }, tbody);
                var tr1 = $common.createElementFromTemplate({ nodeName: "tr" }, tbody);

                // First row
                // EventName
                var td1 = $common.createElementFromTemplate({ nodeName: "td",
                    cssClasses: ['tdNameBet']
                }, tr0);
                td1.innerHTML = String.format('&nbsp;{0}', oBet.get_event_name());
                // TextBox
                var td2 = $common.createElementFromTemplate({ nodeName: "td",
                    properties: { className: 'tdInpBet' }
                }, tr0);
                td2.innerHTML = String.localeFormat('{0:C}', oBet.get_amount());

                // Second row
                // Description
                var td1 = $common.createElementFromTemplate({ nodeName: 'td',
                    cssClasses: ['tdRemarkBet']
                }, tr1);
                td1.innerHTML = oBet.get_description();
                // coefficient
                var td2 = $common.createElementFromTemplate({ nodeName: 'td',
                    properties: { className: 'tdCoefBet' }
                }, tr1);
                td2.innerHTML = oBet.get_factor_desc();
            }
        }
        // COMBI
        var bs_CCB = $get("bs_CCB");
        while (bs_CCB.rows.length != 0) {
            bs_CCB.deleteRow(0);
        }
        // SYSTEMS
        var bs_CSB = $get('bs_CSB');
        while (bs_CSB.rows.length != 0) {
            bs_CSB.deleteRow(0);
        }

        for (var idx in this.sys_collection) {
            var oSBet = this.sys_collection[idx];
            if (!oSBet.is_have_stake())
                continue;

            if (oSBet.BetType == ActiveBets.BetTypes.Combi) {
                var ctr = $common.createElementFromTemplate({ nodeName: "tr" }, bs_CCB)
                var ctd = $common.createElementFromTemplate({ nodeName: 'td',
                    properties: { className: 'tdNabeBetComb' }
                }, ctr);
                ctd.innerHTML = oSBet.get_combi_text();
                var ctd = $common.createElementFromTemplate({ nodeName: 'td',
                    properties: { className: 'tdInpBet' }
                }, ctr);
                ctd.innerHTML = String.localeFormat('{0:C}', oSBet.get_amount());
            }
            else {
                var str = $common.createElementFromTemplate({ nodeName: "tr" }, bs_CSB);
                var std = $common.createElementFromTemplate({ nodeName: "td" }, str);

                var stable = $common.createElementFromTemplate({ nodeName: 'table',
                    properties: { className: 'tabBet' }
                }, std);
                var stbody = $common.createElementFromTemplate({ nodeName: 'tbody' }, stable);
                var str0 = $common.createElementFromTemplate({ nodeName: 'tr' }, stbody);
                // FIRST ROW
                // Text
                var std0 = $common.createElementFromTemplate({ nodeName: 'td',
                    properties: { className: 'tdNabeBetComb', rowSpan: '2' }
                }, str0);
                std0.innerHTML = oSBet.get_system_text();
                // Sum
                var std1 = $common.createElementFromTemplate({ nodeName: 'td',
                    properties: { className: 'tdInpBet' }
                }, str0);
                std1.innerHTML = String.localeFormat('{0:C}', oSBet.get_amount());
            }
        }
        //SUMMARY
        var info = this.get_common_info();
        $get('lCBCount').innerHTML = info.count;
        $get('lCStake').innerHTML = String.localeFormat("{0:C}", info.amount);
        $get('lCWin').innerHTML = String.localeFormat("{0:C}", info.win);
    },

    add_bet: function(/* type = ActiveBets.Bet */oBet) {
        this.pageIndex_change(0);

        this.add_bet_inner(oBet);
        this.update_card();
        this.send_command("add", oBet);
        //this.add_sysbet();
        this.remove_sysbet();
        this.update_sys_bets(this.get_sys_count() - 1); // the last is new and would be not updated
    },

    //    add_sysbet: function() {
    //        var s = this.get_sys_parts_count();
    //        var b = this.get_banks_count();

    //        if (s == 2 && this.sys_collection == 0) {
    //            var scBet = new ActiveBets.SCBet();
    //            Array.add(this.sys_collection, scBet);
    //            this.Single.add_combirow(scBet);
    //            //this.send_command("add", scBet);
    //        }

    //        var min = 2 + (b > 0 ? b - 1 : 0);
    //        var max = s - b > 1 ? s - 1 : 0;

    //        for (var i = min; i <= max; i++) {
    //            if (!this.system_exists(i)) {
    //                var ssBet = new ActiveBets.SSBet(i);
    //                ssBet.set_amount(0);
    //                ssBet.set_stake(0);
    //                Array.add(this.sys_collection, ssBet);
    //                this.Single.add_sysbetrow(ssBet, i - min);
    //                //this.send_command("add", ssBet);
    //            }
    //        }

    //        this.update_sys_limits();
    //        this.check_sys();
    //    },

    system_exists: function(system) {
        for (var i in this.sys_collection)
            if (this.sys_collection[i].get_system() == system)
            return true;

        return false;
    },
    // endregion

    // region [ get ]
    get_amount: function() {
        var amount = 0;

        for (var i in this.collection) {
            var item = this.collection[i];
            amount += item.get_amount();
        }
        for (var i in this.sys_collection) {
            var item = this.sys_collection[i];
            amount += item.get_amount();
        }

        return amount;
    },

    get_bets_count: function() {
        return this.collection.length;
    },

    get_sys_count: function() {
        return this.sys_collection.length;
    },

    get_bet: function(/*ActiveBets.Bet*/oBet) {
        var index = Array.indexOf(this.collection, oBet);
        if (index < 0)
            for (var i in this.collection) {
            if (this.collection[i].equals(oBet)) {
                index = i;
                break;
            }
        }
        if (index < 0)
            return null;
        return this.collection[index];
    },

    get_common_info: function() {
        var singles = this.get_singles_info();
        var systems = this.get_systems_info();

        return { count: singles.count + systems.count, amount: singles.amount + systems.amount, win: singles.win + systems.win };
    },

    // region [ Limits ]
    get_limits_state: function() {
        return this.is_limits_visible;
    },

    set_limits_state: function(value) {
        this.is_limits_visible = value;
    },

    get_banks_state: function() {
        return this.is_banks_visible;
    },

    show_banks: function() {
        this.is_banks_visible = !this.get_banks_state();

        if (this.is_banks_visible) {
            for (var i in this.collection)
                this.collection[i].show_bank(true);
        }
        else {
            for (var i in this.collection) {
                var bet = this.collection[i];
                if (bet.IsBank) {
                    bet.cb_bank.checked = false;
                    bet.set_bank(false);
                }
                bet.show_bank(false);
            }
        }
    },

    show_limits: function() {
        // inverse limits visibility state
        var is_visible = !this.get_limits_state();
        this.set_limits_state(is_visible);
        // Single
        for (var i = 0; i < this.get_bets_count(); i++) {
            this.collection[i].show_limits(is_visible);
        }
        // Sistem
        for (var i in this.sys_collection) {
            this.sys_collection[i].show_limits(is_visible);
        }
    },

    get_stakes_count: function() {
        var count = 0;
        for (var i in this.collection) {
            var oBet = this.collection[i];
            if (oBet.is_have_stake()) count++;
        }
        for (var i in this.sys_collection) {
            var oBet = this.sys_collection[i];
            if (oBet.is_have_stake())
                count += oBet.get_sys_count();
        }
        return count;
    },
    get_sys_min_pay_limit: function() {
        var min_pay = 0.0;
        for (var i = 0; i < this.get_bets_count(); i++) {
            if (!this.collection[i].IsSystemPart)
                continue;
            var bminp = this.collection[i].get_min_pay();
            if (bminp != null && bminp > min_pay)
                min_pay = bminp;
        }
        return min_pay > 0.0 ? min_pay : null;
    },
    get_sys_max_pay_limit: function() {
        var max_pay = 1000000000.0;
        for (var i = 0; i < this.get_bets_count(); i++) {
            if (!this.collection[i].IsSystemPart)
                continue;
            var bmaxp = this.collection[i].get_max_pay();
            if (max_pay == null || (bmaxp != null && bmaxp < max_pay))
                max_pay = bmaxp;
            //        if (this.get_bets_count() > 0)
            //            max_pay = this.collection[0].get_max_pay();
            //        for (var i = 1; i < this.get_bets_count(); i++) {
            //            var bmaxp = this.collection[i].get_max_pay();
            //            if (max_pay == null || (bmaxp != null && bmaxp < max_pay))
            //                max_pay = bmaxp;
        }
        return max_pay > 0.0 ? max_pay : null;
    },
    update_sys_limits: function() {
        var sys_min_pay_limit = this.get_sys_min_pay_limit();
        var sys_max_pay_limit = this.get_sys_max_pay_limit();

        // System
        for (var i = 0; i < this.get_sys_count(); i++) {
            var sBet = this.sys_collection[i];
            sBet.set_limits(sys_min_pay_limit, sys_max_pay_limit);
            sBet.show_limits(this.get_limits_state());
        }
    },
    check_sys: function() {
        var isValid = true;

        for (var i in this.sys_collection) {
            var sBet = this.sys_collection[i];
            var str = [];

            sBet.ErrorCode = ActiveBets.ValidationError.OK;

            if (sBet.OddFactor > ActiveBets.App.get_maxFactor()) {
                sBet.OddFactor = ActiveBets.App.get_maxFactor();
                this.update_bet(sBet);
                sBet.update();

                sBet.ErrorCode |= ActiveBets.ValidationError.OddFactorExceed;
                Array.add(str, Res.FactorExceedError);

                isValid = false;
            }

            if (sBet.OddFactor * sBet.Amount > ActiveBets.App.get_maxPayment()) {
                sBet.set_amount(parseInt(ActiveBets.App.get_maxPayment() / sBet.OddFactor * 100) / 100);
                sBet.set_tb_amount_value(sBet.get_amount());

                if (sBet.StakeType == ActiveBets.BetTypes.System) {
                    sBet.set_stake(sBet.get_amount() / sBet.get_sys_count());
                    sBet.set_tb_stake_value(sBet.get_stake());
                }
                this.update_bet(sBet);
                sBet.update();

                sBet.ErrorCode |= ActiveBets.ValidationError.PossibleWinExceed;
                Array.add(str, Res.WinExceedError);

                isValid = false;
            }

            if (!sBet.check_limits()) {
                this.update_bet(sBet);
                Array.add(str, Res.LimitError);
                isValid = false;
            }

            var error_text = '';
            for (var i in str) {
                error_text += String.format('{0}. {1}<br/>', parseInt(i) + 1, str[i]);
            }
            sBet.set_error(error_text);
        }
        return isValid;
    },
    show_limits_link: function() {
        var bs_show_limits_link = $get('bsShowLimitsLink');

        if (ActiveBets.App.get_user() != null && !ActiveBets.App.get_user().is_anonymous())
            bs_show_limits_link.style.display = '';
        else
            bs_show_limits_link.style.display = 'none';
    },
    // endregion

    // region [ Singles ]
    get_singles_info: function() {
        var amount = 0;
        var win = 0;
        var count = 0;

        for (var i in this.collection) {
            var oBet = this.collection[i];
            if (oBet.is_have_stake()) {
                count += 1;
                amount += oBet.get_amount();
                win += oBet.get_possible_win();
            }
        }

        return { count: count, amount: amount, win: win };
    },

    get_item_by_id: function(id) {
        for (var i in this.collection) {
            if (this.collection[i].equals_by_id(id))
                return this.collection[i];
        }
        return null;
    },

    //    get_item: function(bet) {

    //        for (var i in this.collection) {
    //            if (this.collection[i].equals(bet))
    //                return this.collection[i];
    //        }

    //        return null;
    //    },

    // region [ Combi ]
    get_combi_factor: function() {
        var _oddFactor = 1.0;
        for (var i = 0; i < this.collection.length; i++) {
            var iBet = this.collection[i];
            if (iBet.IsSystemPart)
                _oddFactor *= iBet.get_factor();
        }

        if (_oddFactor > ActiveBets.App.get_maxFactor())
            _oddFactor = ActiveBets.App.get_maxFactor();

        return _oddFactor;
    },

    get_combi_info: function() {
        var amount = 0;
        var win = 0;
        var count = 0;

        if (this.is_combi_available()) {
            var cBet = null;
            for (var i = 0; i < this.collection.length; i++) {
                var cBet = this.sys_collection[i];
                if (cBet.BetType == ActiveBets.BetTypes.Combi)
                    break;
            }
            if (cBet != null && cBet.is_have_stake()) {
                count++;
                amount += cBet.get_amount();
                win += cBet.get_possible_win();
            }
        }
        return { count: count, amount: amount, win: win };
    },
    // endregion [ Combi ]

    // region [ Systems ]
    get_systems_info: function() {
        var amount = 0;
        var win = 0;
        var count = 0;

        for (var i = 0; i < this.sys_collection.length; i++) {
            var ssBet = this.sys_collection[i];
            if (ssBet.is_have_stake()) {
                count += ssBet.get_sys_count(); ;
                amount += ssBet.get_amount();
                win += ssBet.get_possible_win();
            }
        }

        return { count: count, amount: amount, win: win };
    },

    get_sysbet_count: function(system) {
        var count = this.get_sys_parts_count();
        var banks = this.get_banks_count();
        return this._get_system_bets(system - banks, count - banks);
    },

    get_system_factor: function(/* int */system) // result - double
    {
        var combi_arr = []; // factor array
        var bank_arr = [];

        for (var i = 0; i < this.collection.length; i++) {
            var iBet = this.collection[i];
            if (iBet.IsSystemPart && !iBet.IsBank)
                Array.add(combi_arr, iBet.get_factor());
            else if (iBet.IsSystemPart && iBet.IsBank)
                Array.add(bank_arr, iBet.get_factor());
        }

        var factor = Math.round(this._sys_factor(combi_arr, system - this._b_p_c, -1, 1, 0) * 100) / 100;

        for (var i in bank_arr)
            factor = factor * bank_arr[i];

        if (factor > ActiveBets.App.get_maxFactor())
            factor = ActiveBets.App.get_maxFactor();

        return factor;
    },
    //#endregion

    //#region [ remove ]
    remove_bet_inner: function(/* type = ActiveBets.Bet */oBet) {
        Array.remove(this.collection, oBet);
        this.Single.remove_betrow(oBet);
        oBet.select_region(false);
        this.update_s_p_c();
        this.update_b_p_c();
        this.remove_sysbet();
    },

    remove_bet: function(e, /* type = ActiveBets.Bet */oBet) {
        this.remove_bet_inner(oBet);
        this.update_card();
        this.send_command("del", oBet);
        if (this.collection.length == 0)
            this.hide_details_table();
        this.update_sys_limits();
        this.check_sys();
        this.update_sys_bets(this.get_sys_count());
    },

    remove_sysbet: function() {
        var s = this.get_sys_parts_count();
        var b = this.get_banks_count();

        var ca = this.is_combi_available();
        var sa = this.is_system_available();

        var min = 2 + (b > 0 ? b - 1 : 0);
        var max = s - b > 1 ? s - 1 : 0;

        if (!ca) {
            for (var i = this.sys_collection.length - 1; i >= 0; i--) {
                var sBet = this.sys_collection[i];
                Array.remove(this.sys_collection, sBet);
                this.Single.remove_sysbetrow(sBet);
            }
        }
        else {
            for (var i = this.sys_collection.length - 1; i >= 0; i--) {
                var sBet = this.sys_collection[i];
                var system = sBet.get_system();

                if (system != 1) {
                    if (!sa || (system < min || system > max)) {
                        Array.remove(this.sys_collection, sBet);
                        this.Single.remove_sysbetrow(sBet);
                    }
                }
            }

            if (this.sys_collection.length == 0) {
                var scBet = new ActiveBets.SCBet();
                Array.add(this.sys_collection, scBet);
                this.Single.add_combirow(scBet);
                //this.send_command("add", scBet);
            }

            if (sa) {
                for (var i = min; i <= max; i++) {
                    if (!this.system_exists(i)) {
                        var ssBet = new ActiveBets.SSBet(i);
                        ssBet.set_amount(0);
                        ssBet.set_stake(0);
                        Array.add(this.sys_collection, ssBet);
                        this.Single.add_sysbetrow(ssBet, i - min);
                        //this.send_command("add", ssBet);
                    }
                }
            }
        }

        this.update_sys_limits();
        this.check_sys();
    },

    delete_all: function() {
        for (var i = this.collection.length - 1; i >= 0; i--) {
            this.remove_bet_inner(this.collection[i]);
        }
        this.send_command("del_all");
        this.update_card();
        this.hide_details_table();
        this.Single.tabIndex = 500;
    },

    hide_details_table: function() {
        var detailsTable = this.Single.get_details_table();
        detailsTable.style.display = 'none';
    },

    clear_all: function() {
        this.collection = [];
        this.sys_collection = [];
        this.Single.tabIndex = 500;
    },

    clear: function() {
        for (var idx in this.collection) {
            var oBet = this.collection[idx];
            this.Single.remove_betrow(oBet);
            oBet.select_region(false);
        }
        for (var idx in this.sys_collection) {
            var oBet = this.sys_collection[idx];
            this.Single.remove_sysbetrow(oBet);
        }
        this.clear_all();
        this.pageIndex_change(0);
        this.update_card();
    },
    //#endregion [ remove ]

    show_alert: function(message) {
        this.Single.update_alert(true, message);
    },

    //#region [ update ]
    update_card: function() {
        var sys_count = this.get_sys_parts_count();
        var combisystem = this.is_combi_available();

        var isShowAlert = sys_count > 1 ? !combisystem : false;
        this.Single.update_system_alert(isShowAlert);
        if (isShowAlert) {
            this.Single.update_combi({ isAvailable: false });
            this.Single.update_system({ isAvailable: false });
        }
        else {
            var sum_factor = this.get_combi_factor();
            this.Single.update_combi({ isAvailable: combisystem });

            var system = combisystem;
            if (system)
                system = this.is_system_available();

            this.Single.update_system({ isAvailable: system });
            if (system) {
                for (var i in this.sys_collection) {
                    this.sys_collection[i].ui_update();
                }
            }
        }
        var info = this.get_common_info();
        var footer_data = { is_available: true, count: info.count, amount: info.amount, win: info.win };
        this.Single.update_footer(footer_data);
    },

    update_amounts: function() {
        var info = this.get_common_info();

        var footer_data = { is_available: true, count: info.count, amount: info.amount, win: info.win };
        this.Single.update_footer(footer_data);
    },

    update_bet: function(/* type = ActiveBets.Bet*/oBet) {
        this.send_command("upd", oBet);
    },

//    update_sys_bets1: function(count) {
//        for (var idx in this.sys_collection)
//            this.sys_collection[idx].update();
//        //        for (var i = 0; i < count; i++) {
//        //            var ssBet = this.sys_collection[i];
//        //            ssBet.update();
//        //        }
//    },

    update_sys_bets: function() {
        if (this.sys_collection.length > 0) {
            for (var idx in this.sys_collection)
                this.sys_collection[idx].update();
            this.send_command("upds", null);
        }
    },
    //#endregion [ update ]

    get_odd_factor: function(odd_factor) {
        switch (ActiveBets.App.get_oddFormat()) {
            case 'US':
                return ActiveBets.OddsConverter.toAmerican(odd_factor);
                break;
            case 'UK':
                return ActiveBets.OddsConverter.toFractional(odd_factor);
                break;
            default:
                return odd_factor;
                break;
        }
    },

    contains: function(/*ActiveBets.Bet*/oBet) {
        if (Array.contains(this.collection, oBet))
            return true;

        for (var i in this.collection) {
            if (this.collection[i].equals(oBet))
                return true;
        }
        return false;
    },

    get_sys_parts_count: function() {
        return this._s_p_c;
    },

    get_banks_count: function() {
        return this._b_p_c;
    },

    is_combi_available: function() {
        if (this.get_sys_parts_count() >= 2) {
            for (var i = 0; i < this.collection.length; i++) {
                var iBet = this.collection[i];

                if (!iBet.IsSystemPart)
                    continue;

                for (var j = i + 1; j < this.collection.length; j++) {
                    var jBet = this.collection[j];

                    if (!jBet.IsSystemPart)
                        continue;

                    if (iBet.equals_by_event_league(jBet))
                        return false;
                }
            }
            return true;
        }
        return false;
    },

    is_system_available: function() {
        if (this.get_sys_parts_count() > 2) {
            for (var i = 0; i < this.collection.length; i++) {
                var iBet = this.collection[i];

                if (!iBet.IsSystemPart)
                    continue;

                for (var j = i + 1; j < this.collection.length; j++) {
                    var jBet = this.collection[j];

                    if (!jBet.IsSystemPart)
                        continue;

                    if (iBet.equals_by_event_league(jBet))
                        return false;
                }
            }
            return true;
        }
        return false;
    },

    _sys_factor: function(combi_arr, system, step, calcfactor, matched) {
        var _factor = 0.0;
        step++;
        if ((step < this._s_p_c - this._b_p_c) && (matched < system)) {
            _factor += this._sys_factor(combi_arr, system, step, calcfactor, matched);
            _factor += this._sys_factor(combi_arr, system, step, calcfactor * combi_arr[step], matched + 1);
        }
        else if (matched == system) {
            _factor += calcfactor;
        }
        return _factor;
    },

    // region [ command ]
    send_command: function(/* string */command, /**/oBet) {
        var url = "";
        var request = new Sys.Net.WebRequest();
        request.set_userContext({ method: command, item: oBet });
        $wl("send: " + command);
        switch (command) {
            case "add":
                url = String.format("method={0}&stakeType={1}", command, oBet.BetType);
                request.set_httpVerb("POST");
                if (oBet.BetType == ActiveBets.BetTypes.Single)
                    request.set_body(escape(String.format("{0}", this.serialize_item(oBet))));
                else
                    request.set_body(escape(String.format("{0}", this.serialize_system(oBet))));
                request.add_completed(Function.createDelegate(this, this._send_command_callback));
                break;
            case "upd":
                url = String.format("method={0}&stakeType={1}", command, oBet.BetType);
                request.set_httpVerb("POST");
                if (oBet.BetType == ActiveBets.BetTypes.Single)
                    request.set_body(escape(String.format("{0}", this.serialize_item(oBet))));
                else
                    request.set_body(escape(String.format("{0}", this.serialize_system(oBet))));
                request.add_completed(Function.createDelegate(this, this._send_command_callback));
                break;
            case "upds":
                url = String.format("method=upds");
                request.set_httpVerb("POST");
                request.set_body(String.format("s={0}", escape(this.serialize_systems())));
                request.add_completed(Function.createDelegate(this, this._upds_command_callback));
                break;
            case "del":
                url = String.format("method={0}&stakeType={1}", command, oBet.BetType);
                request.set_httpVerb("POST");
                if (oBet.BetType == ActiveBets.BetTypes.Single)
                    request.set_body(escape(String.format("{0}", this.serialize_item(oBet))));
                else
                    request.set_body(escape(String.format("{0}", this.serialize_system(oBet))));
                request.add_completed(Function.createDelegate(this, this._send_command_callback));
                break;
            case "del_all":
                request.set_httpVerb("GET");
                url = String.format("method=del_all");
                break;
        }

        request.set_url(String.localeFormat("{0}Betslip.axd?{1}&tmp={2:dd/MM/yyhh:mm:ss}", this.get_app().get_AppVirtualPath(), encodeURI(url), new Date()));
        request.invoke();
    },

    _send_command_callback: function(executor, eventArgs) {
        var uc = executor.get_webRequest().get_userContext();
        if ((uc == null) || (uc.method == "del"))
            return;

        $wl("callback: " + uc.method);
        var response = Sys.Serialization.JavaScriptSerializer.deserialize(executor.get_responseData());

        if (response.Status == 0) {
            try {
                var bet = uc.item;
                switch (bet.BetType) {
                    case ActiveBets.BetTypes.Single:
                        var iBet = response.Items[0];
                        if (iBet.Limit != null) {
                            bet.set_limits(iBet.Limit.MinPay, iBet.Limit.MaxPay);
                            bet.show_limits(this.get_limits_state());
                            this.update_sys_limits();
                        }
                        break;
                    case ActiveBets.BetTypes.Combi:
                        var sBet = response.Systems[0];
                        bet.set_bonus(sBet.Bonus);
                        bet.ui_update();
                        break;
                }
                this.update_card();
            }
            catch (exc) {
                alert(exc.message);
                throw exc;
            }
        }
    },

    _upds_command_callback: function(executor, eventArgs) {
        var uc = executor.get_webRequest().get_userContext();
        $wl("callback: " + uc.method);
        var response = Sys.Serialization.JavaScriptSerializer.deserialize(executor.get_responseData());
        try {
            var sBet = response.Systems[0];

            for (var i in this.sys_collection) {
                if (this.sys_collection[i].System == 0) {
                    var bet = this.sys_collection[i];
                    bet.set_bonus(sBet.Bonus);
                    bet.ui_update();
                    this.update_card();
                    break;
                }
            }
        }
        catch (exc) {
            alert(exc.message);
            throw exc;
        }
    },

    // endregion [ command ]

    // region [ error ]
    clear_errors: function() {
        for (var i in this.collection) {
            var oBet = this.collection[i];
            oBet.clear_error();
            oBet.disable_inputs(false);
        }

        for (var i in this.sys_collection) {
            var sBet = this.sys_collection[i];
            sBet.clear_error();
        }
    },
    // endregion [ error ]

    _get_system_bets: function(system, count) {
        if (typeof (this.matrix) == "undefined")
            this.matrix = [[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
                      [null, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120],
                      [null, null, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364, 455, 560],
                      [null, null, null, 5, 15, 35, 70, 126, 210, 330, 495, 715, 1001, 1365, 1820],
                      [null, null, null, null, 6, 21, 56, 126, 252, 462, 792, 1287, 2002, 3003, 4368],
                      [null, null, null, null, null, 7, 28, 84, 210, 462, 924, 1716, 3003, 5005, 8008],
                      [null, null, null, null, null, null, 8, 36, 120, 330, 792, 1716, 3432, 6435, 11440],
                      [null, null, null, null, null, null, null, 9, 45, 165, 495, 1287, 3003, 6435, 12870],
                      [null, null, null, null, null, null, null, null, 10, 55, 220, 715, 2002, 5005, 11440],
                      [null, null, null, null, null, null, null, null, null, 11, 66, 286, 1001, 3003, 8008],
                      [null, null, null, null, null, null, null, null, null, null, 12, 78, 364, 1365, 4368],
                      [null, null, null, null, null, null, null, null, null, null, null, 13, 91, 455, 1820],
                      [null, null, null, null, null, null, null, null, null, null, null, null, 14, 105, 560],
                      [null, null, null, null, null, null, null, null, null, null, null, null, null, 15, 120],
                      [null, null, null, null, null, null, null, null, null, null, null, null, null, null, 16]
                      ];
        return this.matrix[system - 1][count - 2];
    },

    serialize_item: function(oBet) {
        return String.format('{{"Id":"{0}", "EventId":{1},"EventCode":"{2}","EventDate":"{3:d} {3:T}","LeagueId":{4},"OddKind":{5},"BetGroupTypeId":{6},"BetTypeId":{7},"BetTypeCode":"{8}","OddId":{9},"OddFactor":{10},"Amount":{11},"HomeTeamName":"{12}","GuestTeamName":"{13}","ColumnIndex":{14},"IsSystemPart":{15},"Limit":{{"MinPay":{16},"MaxPay":{17}}},"BetTypeName":"{18}","EventName":"{19}","OddPoint":{20},"Notes":"{21}", "IsBank":{22}}}',
                oBet.Id, oBet.EventId, oBet.EC, new Date(oBet.EventDate), oBet.LeagueId, oBet.OddKind, oBet.BetGroupTypeId, oBet.BetTypeId, oBet.BetTypeCode, oBet.OddId, oBet.OddFactor, oBet.Amount, oBet.HomeTeamName, oBet.GuestTeamName, oBet.ColumnIndex, oBet.IsSystemPart, oBet.Limits.MinPay != null ? oBet.Limits.MinPay : "null", oBet.Limits.MaxPay != null ? oBet.Limits.MaxPay : "null", oBet.BetTypeName, oBet.EventName, oBet.OddPoint != null ? oBet.OddPoint : "null", oBet.Notes, oBet.IsBank);
    },

    serialize_items: function() {
        var items = "";

        for (var i = 0; i < this.collection.length; i++) {
            items += this.serialize_item(this.collection[i]) + ",";
        }

        if (this.collection.length > 0)
            items = items.substring(0, items.length - 1);

        return String.format("[{0}]", items);
    },

    serialize_system: function(sBet) {
        return String.format('{{"StakeType":{0},"System":{1},"BetCount":{2},"OddFactor":{3},"Amount":{4},"Bonus":{5}}}',
                sBet.BetType, sBet.System != null ? sBet.System : "null", sBet.get_sys_count(), sBet.get_factor(), sBet.get_amount(), sBet._bonus != null ? sBet._bonus : "null");
    },

    serialize_systems: function() {
        var systems = "";

        for (var i = 0; i < this.sys_collection.length; i++) {
            systems += this.serialize_system(this.sys_collection[i]) + ",";
        }

        if (this.sys_collection.length > 0)
            systems = systems.substring(0, systems.length - 1);

        return String.format("[{0}]", systems);
    },

    update_s_p_c: function() {
        this._s_p_c = 0;
        for (var i = 0; i < this.get_bets_count(); i++) {
            var _bet = this.collection[i];
            if (_bet.IsSystemPart)
                this._s_p_c++;
        }
    },

    update_b_p_c: function() {
        this._b_p_c = 0;
        for (var i = 0; i < this.get_bets_count(); i++) {
            var _bet = this.collection[i];
            if (_bet.IsSystemPart && _bet.IsBank)
                this._b_p_c++;
        }
    }
}
ActiveBets.BettingsCard.registerClass("ActiveBets.BettingsCard", Sys.UI.Behavior);
Res={"OddNotExistsError":"Odd not exists.","FactorExceedError":"Odd factor exceeded.","NoLimit":"no lim","LimitError":"Limits: wrong stake","Bet":"Bet","Odd":"Odds","Bonus":"BONUS:","StandartExpress":"Standart express","EventRefundError":"Event refund.","WinExceedError":"Possible win exceeded.","FactorChangedError":"Factor changed.","EventBlockedError":"Event blocked.","EventStartedError":"Event started.","EventDateChangedError":"Event date changed.","Bets":"Bets"};
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();