﻿Type.registerNamespace('ActiveBets');
/*******************  ActiveBets.AccountApp  ***********************/

/*******************  Global functions  ***********************/
var $SelectEvents = function(controlId, /* EventId (int)*/aId) {
    if (aId != null)
        ActiveBets.ExtApp.SelectEvents(controlId, aId);
}

var $SelectLeague = function(/*string*/league_id, /*string*/css, /*string*/css_selected) {
    var sender = $get(league_id);
    sender.className = ActiveBets.ExtApp.SelectLeague(String(league_id)) ? css_selected : css;
}

var $SelectLeagues = function(/*string*/leagues_id, /*string*/css, /*string*/css_selected) {
    if (!$is_set(leagues_id))
        return false;

    var __league_list = ActiveBets.ExtApp.get_leagues();
    for (var i in __league_list) {
        var elt = $get(String(__league_list[i]));
        if (elt)
            elt.className = css;
    }
    ActiveBets.ExtApp.clearLeagues();
    ActiveBets.ExtApp.SelectLeague(leagues_id);
    __league_list = ActiveBets.ExtApp.get_leagues();
    for (var i in __league_list) {
        var elt = $get(String(__league_list[i]));
        if (elt)
            elt.className = css_selected;
    }
}

var $SelectSport = function(/*string*/sport_id) {
    return ActiveBets.ExtApp.SelectSport(sport_id);
}

/*******************  ActiveBets.AccountApp  ***********************/
ActiveBets.AccountApp = function() {

    ActiveBets.AccountApp.initializeBase(this);

    this._user = null;

    this._bett_slip = null;
    this._league_list = [];
    this._event_list = [];
    this._maxStakesCount = null;
    this._lockFlag = false;

    ActiveBets.ExtApp = this;
}
ActiveBets.AccountApp.prototype = {

    _app_onload: function() {
        if (typeof (InitAccordion) != "undefined")
            InitAccordion();

        if (typeof (InitFaq) != "undefined")
            InitFaq();

        if (typeof (InitAccountConditions) != "undefined")
            InitAccountConditions();

        if (typeof (InitBetsConditions) != "undefined")
            InitBetsConditions();

        if (typeof (InitSourcesConditions) != "undefined")
            InitSourcesConditions();

        if (typeof (InitExamplesConditions) != "undefined")
            InitExamplesConditions();

        this._update_accordion();
        this._check_selection();
    },

    _update_accordion: function() {
        if (this._league_list.length > 0)
            for (var i in this._league_list) {
            var elt = $get(String(this._league_list[i]));
            if (elt) elt.className = 'submenuPointSelected';
        }
    },

    get_app: function() {
        return ActiveBets.App;
    },

    get_bett_slip: function() {
        if (this._bett_slip == null) {
            this._bett_slip = $find('BettingsCard');
        }
        return this._bett_slip;
    },

    // region [ User ]

    get_user: function() {
        if (this._user == null)
            this._user = this.get_app().get_user();
        return this._user;
    },

    update_ui: function() {
        if (this.get_user().is_anonymous())
            return;

        var bal_span = $get("user$balance");
        if (bal_span)
            bal_span.innerHTML = String.localeFormat("{0:C}", this.get_user().get_balance());

        var bets_span = $get("user$bets");
        if (bets_span)
            bets_span.innerHTML = String.localeFormat("{0:C}", this.get_user().get_bets_amount());

        if (this.get_bett_slip() == null)
            return;

        if (!this.get_user().is_anonymous())
            this.get_bett_slip().show_limits_link();
        else {
            this.get_bett_slip().show_limits_link();
        }
    },

    // endregion

    // #region [ League List ]
    get_leagues: function() {
        return this._league_list;
    },

    clearLeagues: function() {
        Array.clear(this._league_list);
    },

    SelectLeague: function(/*string*/leagueId) {
        var __arr = leagueId.split('|');
        for (var __i in __arr) {
            var isAdded = !Array.contains(this._league_list, parseInt(__arr[__i]));
            if (isAdded)
                Array.insert(this._league_list, 0, parseInt(__arr[__i]));
            else
                Array.remove(this._league_list, parseInt(__arr[__i]));
        }

        var str = "";
        for (var __i in this._league_list) {
            str += String.format("{0}|", this._league_list[__i]);
        }
        var options = new WebForm_PostBackOptions("ctl00$ctl00$ContentPlaceHolder1$tphLContent$SportAccordion1$leagueCommand", str.substring(0, str.length - 1), false, "", "", false, true);
        this.get_app().DoPostBackWithOptions(options);
        return isAdded;
    },

    SelectEvents: function(controlId, /*string*/eventIds) {
        var __arr = eventIds.split('|');
        this._event_list = [];
        for (var __i in __arr) {
            Array.insert(this._event_list, 0, parseInt(__arr[__i]));
        }
        var options = new WebForm_PostBackOptions(controlId, eventIds, false, "", "", false, true);
        this.get_app().DoPostBackWithOptions(options);
    },

    // #region [ App Routine ]
    SelectSport: function(sportId) {
        var options = new WebForm_PostBackOptions("ctl00$ctl00$ContentPlaceHolder1$tphLContent$SportAccordion1$sportCommand", sportId, false, "", "", false, true);
        this.get_app().DoPostBackWithOptions(options);
    },

    SelectBetType: function(controlId, /*(int)*/betTypeId) {
        var controlName = $get(controlId).name;
        var options = new WebForm_PostBackOptions(controlName, betTypeId, false, "", "", false, true);
        this.get_app().DoPostBackWithOptions(options);
    },
    // #endregion [ App Routine ]

    AcceptWithdaraw: function() {
        var anonymousUserPopup = $find('AnonymousUserPopup');
        var label2 = $get('ErrorText2');
        var label1 = $get('ErrorText1');
        var amount = $get('ctl00_ContentPlaceHolder1_CtrlPaymentWays1_CtrlGetMoney1_txtAmount');
        var name = $get('ctl00_ContentPlaceHolder1_CtrlPaymentWays1_CtrlGetMoney1_txtName');
        var street = $get('ctl00_ContentPlaceHolder1_CtrlPaymentWays1_CtrlGetMoney1_txtStreet');
        var city = $get('ctl00_ContentPlaceHolder1_CtrlPaymentWays1_CtrlGetMoney1_txtCity');
        var accountNumber = $get('ctl00_ContentPlaceHolder1_CtrlPaymentWays1_CtrlGetMoney1_txtAccountNumber');
        var bankCode = $get('ctl00_ContentPlaceHolder1_CtrlPaymentWays1_CtrlGetMoney1_txtBankCode');

        if (amount.value > this._User.get_balance()) {
            label2.style.display = 'block';
            label1.style.display = 'none';
            anonymousUserPopup.show();
            return false;
        }
        else
            if (amount.value == "" || name.value == "" || street.value == "" || city.value == "" || accountNumber.value == "" || bankCode.value == "") {
            label1.style.display = 'block';
            label2.style.display = 'none';
            anonymousUserPopup.show();
            return false;
        }
        else
            return true;
    },

    accept_bets: function() {
        if (!this.get_bett_slip().check_sys() || this._lockFlag)
            return false;

        var anonymousUserPopup = $find('AnonymousUserPopup');

        var result = false;
        if (this.get_user().is_anonymous()) {
            this.show_message(2);
            result = false;
        } else if (this._bett_slip.get_stakes_count() == 0) {
            this.show_message(4);
            result = false;
        } else {
            result = true;
        }
        if (result) {
            this._lockFlag = true;

            var url = String.format("method=val");

            var items = this.get_bett_slip().serialize_items();
            var systems = this.get_bett_slip().serialize_systems();

            var body = String.format("i={0}&s={1}", escape(items), escape(systems));

            var request = new Sys.Net.WebRequest();
            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.set_httpVerb("POST");
            request.set_body(body);
            request.add_completed(Function.createDelegate(this, this._accept_bets_callback));

            request.invoke();
        }

        return false;
    },

    _accept_bets_callback: function(executor, eventArgs) {
        try {
            var response = Sys.Serialization.JavaScriptSerializer.deserialize(executor.get_responseData());

            if (response.Status == 0) {
                this.get_bett_slip().clear_errors();
                this.get_bett_slip()._recreate_confirm();
                this.get_bett_slip().pageIndex_change(1);
            }
            else if (response.Status == 1) {
                this.get_bett_slip().clear_errors();

                this.check_errors(response.Items);
                this.get_bett_slip().pageIndex_change(0);
            }
            else if (response.Status == 10) {
                this.get_bett_slip().clear();
                this.get_bett_slip().pageIndex_change(0);

                this.show_message(6);
            }
        }
        finally {
            this._lockFlag = false;
        }

        return false;
    },

    cancel_bets: function() {
        this.get_bett_slip().pageIndex_change(0);
        return false;
    },

    show_message: function(id) {
        $get('ErrorText1').style.display = 'none';
        $get('ErrorText2').style.display = 'none';
        $get('ErrorText3').style.display = 'none';
        $get('ErrorText4').style.display = 'none';
        $get('ErrorText5').style.display = 'none';
        $get('ErrorText6').style.display = 'none';

        $get('ErrorText' + id).style.display = '';
        $find('AnonymousUserPopup').show();
    },

    clear_betslip: function(controlId) {
        if (this._lockFlag)
            return false;

        this._lockFlag = true;

        var url = String.format("method=accept");

        var request = new Sys.Net.WebRequest();
        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.set_httpVerb("GET");
        request.add_completed(Function.createDelegate(this, this._clear_betslip_callback));
        request.invoke();
    },

    _clear_betslip_callback: function(executor, eventArgs) {
        try {
            var response = Sys.Serialization.JavaScriptSerializer.deserialize(executor.get_responseData());

            if (response.Status == 0) {
                this.get_bett_slip().clear();
                this.get_bett_slip().pageIndex_change(0);
                this.get_app()._update_user();

                this.show_message(5);
            }
            else if (response.Status == 1) {
                this.get_bett_slip().clear_errors();
                this.check_errors(response.Items);
                this.get_bett_slip().pageIndex_change(0);
            }
            else if (response.Status == 2) {
                this.get_bett_slip().pageIndex_change(0);
                this.get_app()._update_user();

                this.show_message(3);

                return false;
            }
            else if (response.Status == 3) {
                this.get_bett_slip().clear_errors();
                this.get_bett_slip().pageIndex_change(0);

                this.show_message(4);
            }
            else if (response.Status == 10) {
                this.get_bett_slip().pageIndex_change(0);

                this.show_message(6);
            }
        }
        finally {
            this._lockFlag = false;
        }

        return false;
    },

    check_errors: function(items) {
        var isValid = true;

        for (var index in items) {
            var iBet = items[index];
            var bet = this.get_bett_slip().get_item_by_id(iBet.Id);
            if (bet == null)
                return;

            bet.set_limits(iBet.Limit.MinPay, iBet.Limit.MaxPay);

            if (iBet.ErrorCode != ActiveBets.ValidationError.OK) {
                isValid = false;

                var str = [];

                // odd not exists
                if ((iBet.ErrorCode & ActiveBets.ValidationError.OddNotExists) > 0) {
                    bet.disable_inputs(true);
                    bet.set_is_system_part(false);
                    Array.add(str, Res.OddNotExistsError);
                }

                // event blocked
                if ((iBet.ErrorCode & ActiveBets.ValidationError.EventBlocked) > 0) {
                    bet.disable_inputs(true);
                    bet.set_is_system_part(false);
                    Array.add(str, Res.EventBlockedError);
                }

                // event date changed
                if ((iBet.ErrorCode & ActiveBets.ValidationError.EventDateChanged) > 0) {
                    bet.EventDate = new Date(iBet.EventDate);
                    Array.add(str, Res.EventDateChangedError);
                }

                // odd factor changed
                if ((iBet.ErrorCode & ActiveBets.ValidationError.OddFactorChanged) > 0) {
                    bet.select_region(false);
                    bet.OddId = iBet.OddId;
                    bet.set_factor(iBet.OddFactor);
                    bet.set_td_factor_innerHTML(bet.get_factor());
                    Array.add(str, Res.FactorChangedError);
                    this.get_bett_slip().update_card();
                    this.get_bett_slip().update_sys_bets(this.get_bett_slip().get_sys_count());
                }

                // event refund
                if ((iBet.ErrorCode & ActiveBets.ValidationError.EventRefund) > 0) {
                    bet.disable_inputs(true);
                    bet.set_is_system_part(false);
                    Array.add(str, Res.EventRefundError);
                }

                // incorrect stake
                if ((iBet.ErrorCode & ActiveBets.ValidationError.IncorrectStake) > 0) {
                    Array.add(str, Res.LimitError);
                    bet.set_amount(iBet.Amount);
                    bet.set_tb_amount_value(bet.get_amount());
                }

                // event started
                if ((iBet.ErrorCode & ActiveBets.ValidationError.EventStarted) > 0) {
                    bet.disable_inputs(true);
                    bet.set_is_system_part(false);
                    Array.add(str, Res.EventStartedError);
                }

                // odd factor exceed
                if ((iBet.ErrorCode & ActiveBets.ValidationError.OddFactorExceed) > 0) {
                    bet.set_factor(iBet.OddFactor);
                    bet.set_td_factor_innerHTML(bet.get_factor());
                    Array.add(str, Res.FactorExceedError);
                    this.get_bett_slip().update_card();
                    this.get_bett_slip().update_sys_bets(this.get_bett_slip().get_sys_count());
                }

                // possible win exceed
                if ((iBet.ErrorCode & ActiveBets.ValidationError.PossibleWinExceed) > 0) {
                    bet.set_amount(iBet.Amount);
                    bet.set_tb_amount_value(bet.get_amount())
                    Array.add(str, Res.WinExceedError);
                }

                var error_text = '';
                for (var i in str) {
                    error_text += String.format('{0}. {1}<br/>', parseInt(i) + 1, str[i]);
                }

                bet.set_error(error_text);
            }
        }

        this.get_bett_slip().update_sys_limits();
        isValid &= this.get_bett_slip().check_sys();

        return isValid;
    },

    _check_selection: function() {
        if (this.get_bett_slip() != null) {
            for (var i in this._bett_slip.collection) {
                var oBet = this._bett_slip.collection[i];
                oBet.check_select_region();
            }
        }
    }
}
ActiveBets.AccountApp.registerClass('ActiveBets.AccountApp');
