/* (c) 2008 www.RuBets.com */
/* Copy and reuse of this code is strictly prohibited */
/* All rights reserved */
/* */

var arube = arube || {};
arube.quickbet = arube.quickbet || {};

arube.quickbet.Base = Class.create({
    tabNavs: new Hash(),
    myBetsBacks: new Hash(),
    myBetsLays: new Hash(),
    myCurrencies: new Hash(),
    myUnmatchedBetsNumber: 0,
    outcomes: new Hash(),
    arenaId: null,

    initialize: function(options) {
        this.options = {
            myBetsRefreshPeriod: 20,  /* seconds */
            myRulesMinRefreshPeriod: 20,  /* seconds */
            title: '',
            locale: "ru",
            loggedUser: false,
            isAuthor: false,
            workCurrencies: { '$' : 10 },
            preferredCurrency: 'p',
            betPanelId: 'ArubeQuickBet',
            title: '',
            startAt : new Date()
        };
        Object.extend(this.options, options || { });
        this.currencies = new Hash();
        
        this.currencies.set( 5, { symbol: 'p' });
        this.currencies.set( 8, { symbol: '€' });
        this.currencies.set( 10, { symbol: '$' });
        this.currencies.set( 11, { symbol: 'f' });
        this.currencies.set( 12, { symbol: 'F' });
        this.currencies.set( 13, { symbol: 'C' });
        this.currencies.get('5').minBet = 5.0;
        this.currencies.get('8').minBet = 0.5;
        this.currencies.get('10').minBet = 0.5;
        this.currencies.get('11').minBet = 2.0;
        this.currencies.get('12').minBet = 2.0;
        this.currencies.get('13').minBet = 1.0;
    },

    mkMainDiv: function() {
        var el = document.createElement("div");
        if(el) {
            el.setAttribute( "id", this.options.betPanelId );
            el.setAttribute( "style", "display:none;" );
            document.body.appendChild(el);
        }
        return el;
    },

    /* returns a dfference in seconds between now and tm */
    getAgo: function (tm) {
        var now = parseInt( (new Date().getTime())/1000 );
        return (now - tm);
    },

    createContainer: function() {
        var inner =
            '<div class="panBodyLeft"><div class="panTop"><div class="panTopLeft"></div></div><div class="panBodyRight"><div class="panBody" style="position:relative;"><div class="panBodyBg"><div class="panBodyContent"><div class="navpan">' +
                '<div class="header"><div class="pad_normal"><span>' +
                    '<a href="javascript:"  style="position:relative; float:right;" class="reload" onclick="' + this.options.varName + '.refreshPlayField(); return false;" id="refresh_playfield_btn' + this.magicCode + '" title="Обновить">&nbsp;</a>' +
                    '<span id="inPlayIcon' + this.magicCode +'" class="' + (this.isInPlayMode() ? 'inPlay' : 'noInPlay') + '">&nbsp;</span>' +
                    '<span id="arena_title' + this.magicCode + '">' + this.options.title + '&nbsp;</span>' +
                '</span></div></div>' +
                '<div class="items"><div class="playField" id="arenaHolder' + this.magicCode +'">' +
                '</div></div></div>' +
            '</div></div></div><div class="panBottom"><div class="panBottomLeft"></div></div></div></div>';
            if ($(this.options.playFieldDiv) != null) {
                $(this.options.playFieldDiv).innerHTML = inner;
                this.options.arenaDiv = 'arenaHolder' + this.magicCode;
            }
    },


    getProfit: function (type, odds, stake) {
        if (type == 'B' || type == 'BL')
            return parseFloat(odds)*parseFloat(stake) - parseFloat(stake);
        else
            return parseFloat(stake);
    },

    getLoss: function (type, odds, stake) {
        if (type == 'B' || type == 'BL')
            return parseFloat(stake);
        else
            return parseFloat(odds)*parseFloat(stake) - parseFloat(stake);
    },

    getSignedProfit: function(type, odds, stake) {
        return (type == 'B' || type == 'BL') ? this.getProfit(type, odds, stake) : -this.getLoss(type, odds, stake);
    },

    getSignedLoss: function(type, odds, stake) {
        return (type == 'B' || type == 'BL') ? this.getLoss(type, odds, stake) : -this.getProfit(type, odds, stake);
    },

    getPayIn: function (type, odds, stake) {
        if (type == 'B' || type == 'BL')
            return parseFloat(stake);
        else
            return parseFloat(odds)*parseFloat(stake) - parseFloat(stake);
    },

    getInvertedStake: function(odds, stake) {
        return Math.floor( ( stake / (odds-1) ) * 100 ) / 100;
    },

    getGhostStake: function(odds, stake) {
        return arube.Utils.formatOdds( (odds-1) * stake );
    },

    showBetTab: function(tab) {
        var __self = this;
        this.tabNavs.each(function(pair) {
            if ($(pair.value.content) != null) {
                if (tab != pair.key) {
                    $(pair.value.content).hide();
                    $(pair.value.nav).className = "navi2";
                }
                else {
                    $(pair.value.content).show();
                    $(pair.value.nav).className = "navi2_selected";
                }
            }
        });
    },

    hideBetTab: function(tabId) {
        if (this.tabNavs.get(tabId) != null) {
            $(this.tabNavs.get(tabId).nav).hide();
        }
    },

    refreshMyRules: function() {
        var __self = this;
        if (__self.getAgo(__self.myRulesUpdated) > __self.options.myRulesMinRefreshPeriod) {
            new Ajax.Updater( 'myRules' + __self.magicCode, '/arube/go/arena/myRules?arena_id=' + __self.arenaId + '&magic_code=' + __self.magicCode,
                { method: 'get'} );
            this.myRulesUpdated = parseInt( (new Date().getTime())/1000 );
        }
    },

    prepareBetPanel: function() {
        var inner =
            '<div class="tabnav" id="tabnav' + this.magicCode +'">' +
                '<div id="betTab1' + this.magicCode +'" name="betNavi" class="navi2_selected">' +
                    '<a href="javascript:" onClick="' + this.options.varName +'.showBetTab(\'MakeABet\'); return false;">' +
                        'Разместить' +
                    '</a>' +
                '</div>' +
                '<div id="betTab2' + this.magicCode +'" name="betNavi" class="navi2">' +
                    '<a href="javascript:" onClick="if (' + this.options.varName +'.options.loggedUser) { ' + this.options.varName +'.showBetTab(\'myBets\'); ' + this.options.varName +'.refreshMyBets();} else {arube.ShowLogin();} return false;">' +
                        'Мои Ставки' +
                    '</a>' +
                '</div>' +
                '<div id="betTab3' + this.magicCode +'" class="navi2">' +
                    '<a href="javascript:" onClick="' + this.options.varName +'.showBetTab(\'myRules\'); ' + this.options.varName +'.refreshMyRules(); return false;">' +
                        'Правила' +
                    '</a>' +
                '</div>' +
            '</div>' +
            '<div style="display:block;" id="MakeABet' + this.magicCode +'" class="MakeABet">' +
                '<div id="requestField' + this.magicCode +'" class="requestField">' +
                    '<div id="B' + this.magicCode +'"></div>' +
                    '<div id="BL' + this.magicCode +'"></div>' +
                    '<div id="L' + this.magicCode +'"></div>' +
                    '<div id="ReqSubmitBottom' + this.magicCode +'" style="display:none;" class="submit">' +
                       '<input class="casual_btn" id="ReqSubmitButton' + this.magicCode +'" type="submit" name="submit" onclick="' + this.options.varName +'.submitRequest(); return false;" value="Вперед!"/>' +
                    '</div>' +
                '</div>' +
                '<div class="modalBetMessageWindow" id="modalMakeABetPanel' + this.magicCode +'" style="top:0; left:0;">' +
                    '<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%">' +
                        '<tr valign="center">' +
                            '<td width="20%"></td><td align="center">' +
                                '<div class="betMessage">Режим В Игре</div>' +
                                '<div class="betComment">Ваша Ставка Будет Размещена Через</div>' +
                                '<div id="MakeABetProgress' + this.magicCode +'" class="betMessage"></div>' +
                            '</td><td width="20%"></td>' +
                        '</tr>' +
                    '</table>' +
                '</div>' +
            '</div>' +
            '<div style="display:none;" id="myBets' + this.magicCode +'" class="myBets">' +
                '<div id="requestField' + this.magicCode +'" class="requestField">' +
                    '<div id="myBetsNew' + this.magicCode +'"></div>' +
                    '<div class="summarybet">' +
                        'Ваша ответственность за парные ставки: <span id="myBetsTotalLiability' + this.magicCode +'"></span><br/>' +
                        'Ваш макс. выигрыш: <span id="myBetsTotalProfit' + this.magicCode +'"></span><br/>' +
                    '</div>' +
                    '<div id="CancelAllUnmatchedBetsBottom' + this.magicCode +'" style="display:none;" class="submit">' +
                       '<input class="casual_btn" id="CancelAllUnmatchedBetsButton' + this.magicCode +'" type="submit" name="submit" ' +
                                'onclick="' + this.options.varName +'.cancelAllUnmatched(); return false;" value="Отменить Все Непарные"/>' +
                    '</div>' +
                '</div>' +
            '</div>' +
            '<div style="display:none;" id="myRules' +  this.magicCode + '" class="myRules">' +
            '</div>';
            if ($(this.options.betPanelId) == null) {
                this.mkMainDiv();
            }
            $(this.options.betPanelId).innerHTML = inner;
    },

    addTabNav: function(navName, contDivName, content) {
        if ($("tabnav"+ this.magicCode) != null) {
            $("tabnav"+ this.magicCode).innerHTML += content;
            this.tabNavs.set( contDivName, { nav: navName, content: contDivName });
        }
    },

    /************** MY BETS TAB ******************************/
    refreshMyBets: function() {
        var __self = this;
        ajaxFacade.getMyBets( this.arenaId, function(resp) {
            if ($('CancelAllUnmatchedBetsBottom' + __self.magicCode) != null) {
                $('CancelAllUnmatchedBetsBottom' + __self.magicCode).style.display = "none";
            }
            __self.myBetsParser(resp);
            __self.myBetsProduceView();
        });
        this.myBetsUpdated = parseInt( (new Date().getTime())/1000 );
    },

    getMyBetsUpdatedAgo: function () {
        var now = parseInt( (new Date().getTime())/1000 );
        return (now - this.myBetsUpdated);
    },

    removeBetRequest: function(id) {
        var __self = this;
        ajaxFacade.arenaRemoveBetRequest( this.arenaId, id, function(resp) {
            __self.removeBetRequestServerResponse( resp );
        });
    },

    removeBetRequestServerResponse: function(res) {
        var msg = arube.Utils.decodeError(res);
        switch (res) {
            case 1:
                /* success*/
                this.refreshMyBets();
                break;
            case 4:
                alert(msg);
                this.refreshMyBets();
                break;
        }
    },

    /* coniders a single request */
    myBetsConsiderSingleRequest: function(outcome, type, currency, odds, stake) {
        if (typeof this.myBetsOutcomes.get( outcome ) == 'undefined')
            this.myBetsOutcomes.set( outcome, new Array() );
        var pol = this.myBetsOutcomes.get( outcome );
        /* calculate liability */
        if (typeof pol['persLiability'] == 'undefined')
            pol['persLiability'] = new Hash();
        if (typeof pol['persLiability'].get(currency) == 'undefined')
            pol['persLiability'].set( currency, 0 );
        pol['persLiability'].set( currency,
            pol['persLiability'].get(currency) + this.getSignedLoss( type, odds, stake ) );
        /* calculate profit: */
        if (typeof pol['persProfitAndLoss'] == 'undefined')
            pol['persProfitAndLoss'] = new Hash();
        if (typeof pol['persProfitAndLoss'].get(currency) == 'undefined')
            pol['persProfitAndLoss'].set( currency, 0 );
        pol['persProfitAndLoss'].set( currency,
            pol['persProfitAndLoss'].get(currency) + this.getSignedProfit( type, odds, stake ) );
    },

    myBetsConsiderProfitAndLoss: function(bets) {
        var __self = this;
        bets.each(function(pair) {
            var params = pair.value;
            /* 23.04.2009: logic was changed, unmatched bets are not considered anymore
                    if (typeof params['status'] != 'undefined' && (params['status'] == 1 || params['status'] == 2)) { */
            if (typeof params['status'] != 'undefined' && params['status'] == 2) {
                __self.myBetsConsiderSingleRequest(params['outcome'], params['type'], params['currency'], params['odds'], params['stake'] );
            }
        });
    },

    myBetsGetPersonalProfitAndLoss: function(outcome, currency) {
        if (typeof outcome == 'undefined' || typeof outcome['persProfitAndLoss'] == 'undefined' ||
                typeof outcome['persProfitAndLoss'].get(currency) == 'undefined')
        {
            return 0.0;
        }
        return outcome['persProfitAndLoss'].get(currency);
    },

    myBetsGetPersonalLiability: function(outcome, currency) {
        if (typeof outcome == 'undefined' || typeof outcome['persLiability'] == 'undefined' ||
                typeof outcome['persLiability'].get(currency) == 'undefined')
        {
            return 0.0;
        }
        return outcome['persLiability'].get(currency);
    },

    /* Loads general info about the arena. e.g.: arena name, outcome ids & names, order */
    loadArenaInfo: function() {
        var __self = this;
        ajaxFacade.getArenaInfo( this.arenaId, this.options.locale, function(resp) {
            __self.arenaInfoResponse( resp );
        });
    },

    eventId: null,
    marketId: null,
    startAt: null,
    arenaName: null,

    arenaInfoResponse: function(resp) {
        this.outcomes = new Hash();
        this.myBetsOutcomes = new Hash();
        var lines = resp.split('\n');
        for(var i = 0; i < lines.length; i++) {
            if (lines[i] != "") {
                var params = arube.Utils.parseServerResponse( lines[i] );
                if (typeof params['arena_id'] != 'undefined' && !isNaN(params['arena_id'])) {
                    eventId = params['event_id'];
                    marketId = params['market_id'];
                    startAt = params['start_at'];
                    arenaName = params['arena_name'];
                }
                else
                if (typeof params['outcome_id'] != 'undefined' && !isNaN(params['outcome_id'])) {
                    this.outcomes.set( params['outcome_id'], {
                        id: params['outcome_id'],
                        order: params['order'],
                        name: params['name']
                    });
                    this.myBetsOutcomes.set( params['outcome_id'], undefined );
                }
            }
        }

        if (this.outcomes.size() == 0) {
            /* destroy popup */
            tt_HideInit();
        }
    }
});

arube.quickbet.OddsBetting = Class.create(arube.quickbet.Base, {

    myBetsOutcomes: new Hash(),
    reloadProgressTurnedOn: 0,
    magicCode: 0,
    myBetsUpdated: 0,
    myRulesUpdated: 0,
    betStorage: null,

    initialize: function($super, arenaId, options) {
        $super(options);
        this.arenaId = arenaId;
        this.magicCode = '_qm' + arenaId + 'a' + new Date().getTime() % 1000;
        this.loadArenaInfo();

        this.options.betPanelId += this.magicCode;

        this.tabNavs.set(  'MakeABet', { content: 'MakeABet' + this.magicCode, nav: 'betTab1' + this.magicCode } );
        this.tabNavs.set( 'myBets', { content: 'myBets' + this.magicCode, nav: 'betTab2' + this.magicCode } );
        this.tabNavs.set( 'myRules', { content: 'myRules' + this.magicCode, nav: 'betTab3' + this.magicCode } );

        this.prepareBetPanel();
        this.refreshMyRules();

        this.betStorage = $H({
            B: new Hash(), /* Backs */
            L: new Hash(), /* Lays */
            BL: new Hash() /* Backs of Lay type (bookie style) */
        });
        TagToTip( this.options.betPanelId, COPYCONTENT, false, PADDING, 5, BORDERWIDTH, 1, WIDTH, 360, TITLE, 'Быстрая ставка', STICKY, true, HEIGHT, 250, CLOSEBTN, true, BGCOLOR, '#333');
    },

    /**
     *  TODO: replace outcomeName with this.outcomes(id).name. Usually on the time when
     *        this function is being called, this.outcomes is not filled in yet. (wait or workaround)
     *  Required fields in opts: opts.type, opts.oid, opts.odds, opts.currency
     *
     **/
    addBet: function(opts) {
        this.showBetTab( 'MakeABet' );

        var elem = $( opts.type + opts.oid + this.magicCode );
        var parent = $( opts.type + this.magicCode );

        if (elem == null) {
            var bets = this.betStorage.get(opts.type);

            if (typeof(bets) != 'undefined' && bets != null) {
                if (bets.size() == 0) {
                    parent.appendChild( this.produceHeader( opts.type ) );
                }
                opts.form = this.createNewReqDiv(opts.type, opts.oid, opts.ouname, opts.odds, opts.currency, opts.origOdds);
                parent.appendChild( opts.form );
                bets.set( opts.oid, opts );
                this.calculateInputProfitAndLoss(opts.type, opts.oid);
                /*$(type + 'Stake' + id + this.magicCode).focus(); */
            }
        }
        else {
            this.removeBet( opts.type, opts.oid )
        }
        this.showSubmitButton();
    },

    betFormsExist: function() {
        var found = false;
        this.betStorage.each(function(pair) {
            var bets = pair.value;
            if (typeof bets != 'undefined' && bets != null && bets.size() > 0) {
                found = true;
            }
        });
        return found;
    },

    showSubmitButton: function() {
        if (this.betFormsExist()) {
            $( "ReqSubmitBottom" + this.magicCode ).show();
        }
        else {
            $( "ReqSubmitBottom" + this.magicCode ).hide();
        }
    },

    removeBet: function(type, id, keepWindow) {
        var bets = this.betStorage.get(type);
        var parent = $( type + this.magicCode );
        parent.removeChild( bets.get(id).form );
        bets.unset(id);
        if (bets.size() <= 0) {
            parent.removeChild( $( "head" + type + this.magicCode  ) );
        }
        if ((typeof keepWindow == 'undefined' || !keepWindow) && !this.betFormsExist()) {
            tt_HideInit();
        }
        this.showSubmitButton();
        /*this.myBetsCalculateProfitAndLoss();*/
    },

    produceHeader: function(type) {

        var newDiv = document.createElement('div');
        newDiv.setAttribute('id', 'head' + type + this.magicCode );

        if (type == 'B') {
            newDiv.setAttribute('class', 'backbet' );
            newDiv.innerHTML =
                '    <table border="0" cellspacing="0" cellpadding="1" class="backbet">' +
                '        <tr>' +
                '           <th width="200px" style="text-align:left;">За</th>' +
                '           <th width="70px">Ваш коэф.</th>' +
                '            <th width="110px">Ваша ставка</th>' +
                '       </tr>' +
                '    </table>';
        }
        else
        if (type == 'BL') {
            newDiv.setAttribute('class', 'laybet' );
            newDiv.innerHTML =
                '    <table border="0" cellspacing="0" cellpadding="1" class="laybet">' +
                '        <tr>' +
                '           <th width="200px" style="text-align:left;">Против</th>' +
                '           <th width="70px">Ваш коэф.</th>' +
                '            <th width="110px">Ваша ставка</th>' +
                '       </tr>' +
                '    </table>';
        }
        else {
            newDiv.setAttribute('class', 'laybet' );
            newDiv.innerHTML =
                '    <table border="0" cellspacing="0" cellpadding="1" class="laybet">' +
                '        <tr>' +
                '            <th width="200px" style="text-align:left;">Против</th>' +
                '            <th width="70px" align="center">Коэф. противника</th>' +
                '            <th width="110px" align="center">Ставка противника</th>' +
                '        </tr>' +
                '    </table>';
        }
        return newDiv;
    },

    /* if user misstyped, let's not complain, just fix it quiet */
    FixFloat: function(id) {
        if ($(id) != null) {
            var num = arube.Utils.fixFloat($(id).getValue());
            $(id).setValue(num);
        }
    },

    /* call it each time user presses a key in request Back box or changes something */
    OnBackType: function(id) {
        this.calculateProfit('B', id);
    },

    /* call it each time user presses a key in request Back box or changes something */
    OnBackLayType: function(id) {
        this.calculateProfit('BL', id);
        /*this.calculateLiability('BL', id); */
    },

    /* call it each time user presses a key in request Lay box or changes something */
    OnLayType: function(id) {
        this.calculateLiability('L', id);
    },

    calculateInputProfitAndLoss: function(type, id) {
        if (type == 'B' || type == 'BL') {
            this.calculateProfit( type, id );
        }
        else
        if (type == 'L') {
            this.calculateLiability( type, id );
        }
    },

    calculateProfit: function(type, id) {
        var elemProfit = $( type + "Profit" + id + this.magicCode );
        var elemOdds = $( type + "Odds" + id + this.magicCode );
        var elemStake = $( type + "Stake" + id + this.magicCode);
        var elemCurrency = $( type + 'Currency'+id+ this.magicCode);
        if (elemProfit != null && elemOdds != null && elemStake != null) {
            elemProfit.innerHTML = '+' + arube.Utils.formatCurrency( this.getProfit( type, elemOdds.value, elemStake.value ), elemCurrency.value );
        }
        var elemLoose = $(type + "Loss" + id+ this.magicCode );
        if (elemLoose != null && elemStake != null) {
            elemLoose.innerHTML = '-' + arube.Utils.formatCurrency( this.getLoss( type, elemOdds.value, elemStake.value ), elemCurrency.value );
        }
        var elemPayIn = $(type + "PayIn" + id + this.magicCode );
        if (elemPayIn != null && elemStake != null) {
            elemPayIn.innerHTML = arube.Utils.formatCurrency( this.getPayIn( type, elemOdds.value, elemStake.value ), elemCurrency.value );
        }
    },

    calculateLiability: function(type, id) {
        var elemLiability = $(type + "Liability" + id + this.magicCode );
        var elemOdds = $(type + "Odds" + id + this.magicCode ) != null ? $(type + "Odds" + id + this.magicCode ).value : null;
        var elemStake = $(type + "Stake" + id + this.magicCode ) != null ? $(type + "Stake" + id + this.magicCode ).value : null;
        var elemCurrency = $(type + 'Currency'+id + this.magicCode );
        if (type == 'BL') {
            var bet = this.betStorage.get(type).get(id);
            if (typeof bet != 'undefined') {
                elemOdds = bet.origOdds;
                elemStake = this.getInvertedStake( bet.origOdds, elemStake );
            }
        }
        if (elemLiability != null && elemOdds != null && elemStake != null) {
            elemLiability.innerHTML = '-' + arube.Utils.formatCurrency( this.getLoss( type, elemOdds, elemStake ), elemCurrency.value );
        }
        var elemProfit = $(type + "Profit" + id + this.magicCode );
        if (elemProfit != null && elemStake != null) {
            elemProfit.innerHTML = '+' + arube.Utils.formatCurrency( this.getProfit( type, elemOdds, elemStake ), elemCurrency.value );
        }
        var elemPayIn = $(type + "PayIn" + id + this.magicCode );
        if (elemPayIn != null && elemStake != null && elemOdds != null) {
            elemPayIn.innerHTML = arube.Utils.formatCurrency( this.getPayIn( type, elemOdds, elemStake ), elemCurrency.value );
        }
    },

    createNewReqDiv: function(type, id, outcomeName, defOdds, defCurrency, origOdds) {
        var text=null;
        defOdds = defOdds != null ? defOdds : 2.00;
        defCurrency = defCurrency != null ? defCurrency : 10;

        var newDiv = document.createElement('div');
        newDiv.setAttribute('id', type + id + this.magicCode);

        if (type == "B") {
            newDiv.setAttribute('class', "backbetDiv" );
            var html =
              '<table border="0" cellspacing="0" cellpadding="1" class="backbetDiv">' +
                  '<tr>' +
                      '<td width="200px" style="text-align:left; padding: 0 4px;" valign="top">' +
                          '<input type="submit" class="smallBtn" onClick="' + this.options.varName +'.removeBet(\'' + type + '\', '+ id +');return false;" value="&nbsp;X&nbsp;" title="Закрыть" >' +
                          '<span class="name">&nbsp;'+ outcomeName +'</span>' +
                      '</td>' +
                      '<td width="90px"><div class="odds">' +
                         '<input class="input" type="text" size="6" maxlength="6" value="'+ defOdds +'" name="BOdds'+ id + this.magicCode +'" id="BOdds'+ id + this.magicCode +'"  ' +
                            'onChange="' + this.options.varName +'.FixFloat(\'BOdds' + id + this.magicCode+ '\'); ' + this.options.varName +'.OnBackType('+id +');" onkeyup="' + this.options.varName +'.OnBackType('+id +');"/>' +
                          '<div class="plus_minus_container">' +
                              '<a href="javascript:" onClick="arube.Utils.increaseEditBox(\'BOdds'+ id + this.magicCode + '\', 0.01); ' + this.options.varName +'.OnBackType('+id +'); return false;" class="numb_plus"></a>' +
                              '<a href="javascript:" onClick="arube.Utils.increaseEditBox(\'BOdds'+ id + this.magicCode +'\', -0.01); ' + this.options.varName +'.OnBackType('+id +'); return false;" class="numb_minus"></a>' +
                      '</div></div></td>' +
                      '<td width="110px" align="right"><input class="input" type="text" size="6" maxlength="6" name="BStake'+ id + this.magicCode+'" id="BStake'+ id + this.magicCode+'" '+
                            'onChange="' + this.options.varName +'.FixFloat(\'BStake' + id + this.magicCode+ '\'); ' + this.options.varName +'.OnBackType('+id +');" onkeyup="' + this.options.varName +'.OnBackType('+id +');"/>' +
                      '<select class="input" name="BCurrency'+ id + this.magicCode+'" id="BCurrency'+ id + this.magicCode +'"  onChange="' + this.options.varName +'.OnBackType('+id +'); return false;">';
            if (typeof this.options.workCurrencies !=  'undefined' && this.options.workCurrencies != null) {
                this.options.workCurrencies.each(function(pair) {
                   html +=  '<option value="'+ pair.key + '" ' + (pair.key == defCurrency ? "selected" : "") +'>' + pair.value + '</option>';
                });
            }
            html +=
                     '</select>' +
                     '</td>' +
                '</tr>' +
                '<tr><td colspan="3">' +
                '<table border="0" cellpadding="0" cellspacing="4px" class="backbetDiv">' +
                '<tr>' +
                   '<td colspan="2" class="comment">Вы ставите НА победу "' + outcomeName +'"  '+
                       '<span class="commentError" id="BStatus' + id + this.magicCode+ '"></span></td>'  +
                '</tr>' +
                '<tr>' +
                   '<td class="comment">Ваша ставка:</td>' +
                   '<td class="stake"><div id="BPayIn'+id+ this.magicCode+ '"></div></td>' +
                '</tr>' +
                '<tr>' +
                   '<td class="comment">Если "' + outcomeName +'" победит, вы получите обратно вашу ставку плюс:</td>' +
                   '<td class="profit"><div id="BProfit'+id+ this.magicCode+'"></div></td>' +
                '</tr>' +
                '<tr>' +
                   '<td class="comment">Если "' + outcomeName +'" НЕ победит, вы потеряете вашу ставку:</td>' +
                   '<td class="loose"><div id="BLoss'+id+ this.magicCode+'"></div></td>' +
                '</tr>' +
                '<tr>' +
                   '<td class="comment">Отменять непарную ставку при переходе в In-Play?</td>' +
                   '<td class="loose"><input type="checkbox" id="BCancelOnStart'+id+ this.magicCode+'" CHECKED></td>' +
                '</tr>' +
                '</table>'+
                '</td></tr>' +
            '</table>';
            newDiv.innerHTML = html;
        }
        else
        if (type == "BL") {
            newDiv.setAttribute('class', "laybetDiv" );
            var html =
              '<table border="0" cellspacing="0" cellpadding="1" class="laybetDiv">' +
                  '<tr>' +
                      '<td width="200px" style="text-align:left; padding: 0 4px;" valign="top">' +
                          '<input type="submit" class="smallBtn" onClick="' + this.options.varName +'.removeBet(\'' + type + '\', '+ id +');return false;" value="&nbsp;X&nbsp;" title="Закрыть" >' +
                          '<span class="name">&nbsp;'+ outcomeName +'</span>' +
                      '</td>' +
                      '<td width="90px"><div class="odds">' +
                         '<input readonly="true" class="input" type="text" size="6" maxlength="6" value="'+ defOdds +'" name="BLOdds'+ id + this.magicCode +'" id="BLOdds'+ id + this.magicCode +'"  ' +
                            'onChange="' + this.options.varName +'.FixFloat(\'BLOdds' + id + this.magicCode+ '\'); ' + this.options.varName +'.OnBackLayType('+id +');" onkeyup="' + this.options.varName +'.OnBackLayType('+id +');"/>' +
                      '</div></td>' +
                      '<td width="110px" align="right"><input class="input" type="text" size="6" maxlength="6" name="BLStake'+ id + this.magicCode+'" id="BLStake'+ id + this.magicCode+'" '+
                            'onChange="' + this.options.varName +'.FixFloat(\'BLStake' + id + this.magicCode+ '\'); ' + this.options.varName +'.OnBackLayType('+id +');" onkeyup="' + this.options.varName +'.OnBackLayType('+id +');"/>' +
                      '<select class="input" name="BLCurrency'+ id + this.magicCode+'" id="BLCurrency'+ id + this.magicCode +'"  onChange="' + this.options.varName +'.OnBackLayType('+id +'); return false;">';
            if (typeof this.options.workCurrencies !=  'undefined' && this.options.workCurrencies != null) {
                this.options.workCurrencies.each(function(pair) {
                   html +=  '<option value="'+ pair.key + '" ' + (pair.key == defCurrency ? "selected" : "") +'>' + pair.value + '</option>';
                });
            }
            html +=
                     '</select>' +
                     '</td>' +
                '</tr>' +
                '<tr><td colspan="3">' +
                '<table border="0" cellpadding="0" cellspacing="4px" class="laybetDiv">' +
                '<tr>' +
                   '<td colspan="2" class="comment">Вы ставите ПРОТИВ победы "' + outcomeName +'"  '+
                       '<span class="commentError" id="BLStatus' + id + this.magicCode+ '"></span></td>'  +
                '</tr>' +
                '<tr>' +
                   '<td class="comment">Ваша ставка:</td>' +
                   '<td class="stake"><div id="BLPayIn'+id+ this.magicCode+ '"></div></td>' +
                '</tr>' +
                '<tr>' +
                   '<td class="comment">Если "' + outcomeName +'" НЕ победит, вы получите назад вашу ставку плюс:</td>' +
                   '<td class="profit"><div id="BLProfit'+id+ this.magicCode+'"></div></td>' +
                '</tr>' +
                '<tr>' +
                   '<td class="comment">Если "' + outcomeName +'" победит, вы потеряете вашу ставку:</td>' +
                   '<td class="loose"><div id="BLLoss'+id+ this.magicCode+'"></div></td>' +
                '</tr>' +
                '<tr>' +
                   '<td class="comment">Отменять непарную ставку при переходе в In-Play?</td>' +
                   '<td class="loose"><input type="checkbox" id="BLCancelOnStart'+id+ this.magicCode+'" CHECKED></td>' +
                '</tr>' +
                '</table>'+
                '</td></tr>' +
            '</table>';
            newDiv.innerHTML = html;
        }
        else
        /* uncomment or remove it when it will be decided which approach on placing 1X bets to use */
        /*if (type == "BL") {
            newDiv.setAttribute('class', "laybetDiv" );
            var html =
              '<table border="0" cellspacing="0" cellpadding="1" class="laybetDiv">' +
                  '<tr>' +
                      '<td width="200px" style="text-align:left; padding: 0 4px;" valign="top">' +
                          '<input type="submit" class="smallBtn" onClick="' + this.options.varName +'.removeBet(\'' + type + '\', '+ id +');return false;" value="&nbsp;X&nbsp;" title="Закрыть" >' +
                          '<span class="name">&nbsp;'+ outcomeName +'</span>' +
                      '</td>' +
                      '<td width="90px"><div class="odds">' +
                         '<input readonly="true" class="input" type="text" size="6" maxlength="6" value="'+ defOdds +'" name="BLOdds'+ id + this.magicCode +'" id="BLOdds'+ id + this.magicCode +'"  ' +
                            'onChange="' + this.options.varName +'.FixFloat(\'BLOdds' + id + this.magicCode+ '\'); ' + this.options.varName +'.OnBackLayType('+id +');" onkeyup="' + this.options.varName +'.OnBackLayType('+id +');"/>' +
                      '</div></td>' +
                      '<td width="110px" align="right"><input class="input" type="text" size="6" maxlength="6" name="BLStake'+ id + this.magicCode+'" id="BLStake'+ id + this.magicCode+'" '+
                            'onChange="' + this.options.varName +'.FixFloat(\'BLStake' + id + this.magicCode+ '\'); ' + this.options.varName +'.OnBackLayType('+id +');" onkeyup="' + this.options.varName +'.OnBackLayType('+id +');"/>' +
                      '<select class="input" name="BLCurrency'+ id + this.magicCode+'" id="BLCurrency'+ id + this.magicCode +'"  onChange="' + this.options.varName +'.OnBackLayType('+id +'); return false;">';
            if (typeof this.options.workCurrencies !=  'undefined' && this.options.workCurrencies != null) {
                this.options.workCurrencies.each(function(pair) {
                   html +=  '<option value="'+ pair.key + '" ' + (pair.key == defCurrency ? "selected" : "") +'>' + pair.value + '</option>';
                });
            }
            html +=
                       '</select>' +
                       '</td>' +
                  '</tr>' +
                  '<tr><td colspan="3">' +
                  '<table border="0" cellpadding="0" cellspacing="4px" class="laybetDiv">' +
                  '<tr>' +
                     '<td colspan="2" class="comment">Вы ставите ПРОТИВ победы "' + outcomeName +'" ' +
                         '<span class="commentError" id="BLStatus' + id + this.magicCode+ '"></span></td>'  +
                  '</tr>' +
                  '<tr>' +
                     '<td class="comment">Ваша ставка:</td>' +
                     '<td class="stake"><div id="BLPayIn'+id+ this.magicCode+'"></div></td>' +
                  '</tr>' +
                  '<tr>' +
                     '<td class="comment">Обратный коэффициент противника <a href="http://docs.rubets.com/index.php?id=40" title="получить справку" target="blank_">?</a></td>' +
                     '<td class="stake"><div id="BLCoeff'+id+ this.magicCode+'"><b>' + origOdds + '</b></div></td>' +
                  '</tr>' +
                  '<tr>' +
                     '<td class="comment">Если "' + outcomeName +'" НЕ победит, вы получите назад вашу ставку плюс ставку противника:</td>' +
                     '<td class="profit"><div id="BLProfit'+id+ this.magicCode+'"></div></td>' +
                  '</tr>' +
                  '<tr>' +
                     '<td class="comment">Если "' + outcomeName +'" победит, вы потеряете вашу ставку:</td>' +
                     '<td class="loose"><span id="BLLiability'+id+ this.magicCode+'"></span></td>' +
                  '</tr>' +
                  '<tr>' +
                    '<td class="comment">Отменять непарную ставку при переходе в In-Play?</td>' +
                    '<td class="loose"><input type="checkbox" id="BLCancelOnStart'+id+'" CHECKED></td>' +
                  '</tr>' +
                  '</table>'+
                  '</td></tr>' +
              '</table>';
            newDiv.innerHTML = html;
        }
        else */
        {
            newDiv.setAttribute('class', "laybetDiv" );
            var html =
                '<table border="0" cellspacing="0" cellpadding="1" class="laybetDiv">' +
                    '<tr>' +
                          '<td width="200px" style="text-align:left; padding: 0 4px;" valign="top">' +
                            '<input type="submit" class="smallBtn" onClick="' + this.options.varName +'.removeBet(\'' + type + '\', '+ id +');return false;" value="&nbsp;X&nbsp;" title="Закрыть" >' +
                            '<span class="name">'+ outcomeName +'</span>' +
                        '</td>' +
                        '<td width="90px"><div class="odds">' +
                                 '<input class="input" type="text" size="6" maxlength="6" value="'+ defOdds +'" name="LOdds'+ id + this.magicCode +'" id="LOdds'+ id + this.magicCode +'"  '+
                                     'onChange="' + this.options.varName +'.FixFloat(\'LOdds'+id+ this.magicCode+'\'); ' + this.options.varName +'.OnLayType('+id+');" onkeyup="' + this.options.varName +'.OnLayType('+id+');"/>' +
                          '<div class="plus_minus_container">' +
                                '<a href="javascript:" onClick="arube.Utils.increaseEditBox(\'LOdds'+ id + this.magicCode +'\', 0.01); ' + this.options.varName +'.OnLayType('+id+'); return false;" class="numb_plus"></a>' +
                                '<a href="javascript:" onClick="arube.Utils.increaseEditBox(\'LOdds'+ id + this.magicCode +'\', -0.01); ' + this.options.varName +'.OnLayType('+id+'); return false;" class="numb_minus"></a>' +
                        '</div></div></td>' +
                        '<td width="110px"><input class="input" type="text" size="6" maxlength="6" name="LayStake'+ id + this.magicCode+'" id="LayStake'+ id + this.magicCode+'" ' +
                            'onChange="' + this.options.varName +'.FixFloat(\'LStake'+id+ this.magicCode+'\'); ' + this.options.varName +'.OnLayType('+id+');" onkeyup="' + this.options.varName +'.OnLayType('+id+');"/>' +
                        '<select class="input" name="LCurrency'+ id+ this.magicCode+'" id="LCurrency'+ id + this.magicCode+'" onChange="' + this.options.varName +'.OnLayType('+id+'); return false;">';
            if (typeof this.options.workCurrencies !=  'undefined' && this.options.workCurrencies != null) {
                this.options.workCurrencies.each(function(pair) {
                   html += '<option value="'+ pair.key + '" ' + (pair.key == defCurrency ? "selected" : "") +'>' + pair.value + '</option>';
                });
            }
            html +=
                       '</select>' +
                       '</td>' +
                  '</tr>' +
                  '<tr><td colspan="3">' +
                  '<table border="0" cellpadding="0" cellspacing="4px" class="laybetDiv">' +
                  '<tr>' +
                     '<td colspan="2" class="comment">Вы ставите ПРОТИВ победы "' + outcomeName +'" ' +
                         '<span class="commentError" id="LStatus' + id + this.magicCode+ '"></span></td>'  +
                  '</tr>' +
                  '<tr>' +
                     '<td class="comment">Ваша ставка:</td>' +
                     '<td class="stake"><div id="LPayIn'+id+ this.magicCode+'"></div></td>' +
                  '</tr>' +
                  '<tr>' +
                     '<td class="comment">Если "' + outcomeName +'" НЕ победит, вы получите назад вашу ставку плюс ставку противника:</td>' +
                     '<td class="profit"><div id="LProfit'+id+ this.magicCode+'"></div></td>' +
                  '</tr>' +
                  '<tr>' +
                     '<td class="comment">Если "' + outcomeName +'" победит, вы потеряете вашу ставку:</td>' +
                     '<td class="loose"><span id="LLiability'+id+ this.magicCode+'"></span></td>' +
                  '</tr>' +
                  '<tr>' +
                    '<td class="comment">Отменять непарную ставку при переходе в In-Play?</td>' +
                    '<td class="loose"><input type="checkbox" id="LCancelOnStart'+id+'" CHECKED></td>' +
                  '</tr>' +
                  '</table>'+
                  '</td></tr>' +
              '</table>';
            newDiv.innerHTML = html;
        }
        return newDiv;
    },

    inPlayTimeout: null,
    inPlayTimeoutVal: 10,

    isInPlayMode: function() {
        return false;
    },

    submitRequest: function() {
        if (this.options.loggedUser == false) {
            arube.ShowLogin();
        }
        else {
            var req = '', err = false;
            var __self = this;
            this.betStorage.each(function(formPair) {
                var bets = formPair.value;
                var type = formPair.key;
                if (typeof(bets) != 'undefined' && bets != null && bets.size() > 0) {
                    bets.each(function(betPair) {
                        var keyB = betPair.key;
                        if (typeof keyB != 'undefined') {
                            var oddsB = $( type + 'Odds'+ keyB + __self.magicCode );
                            var stakeB = $(  type + 'Stake'+keyB + __self.magicCode);
                            var currencyB = $(type + 'Currency'+keyB + __self.magicCode);
                            var cancelB = $(type + 'CancelOnStart' + keyB + __self.magicCode);
                            if (isNaN(parseFloat(oddsB.getValue())) || parseFloat(oddsB.getValue()) < 1.01 || parseFloat(oddsB.getValue()) > 1000.0) {
                                oddsB.focus(); oddsB.select(); err = true;
                                alert( arube.Utils.decodeError(102) );
                                return;
                            }
                            if (isNaN(parseFloat(stakeB.getValue())) || parseFloat(stakeB.getValue()) < __self.currencies.get(currencyB.getValue()).minBet) {
                                stakeB.focus(); stakeB.select(); err = true;
                                alert( arube.Utils.decodeError(101) + ' ' + __self.currencies.get(currencyB.getValue()).minBet +arube.Utils.decodeCurrency( currencyB.getValue(), true) );
                                return;
                             }
                             if (req != '') req += '\n';
                             req += 'outcomeId='+keyB+';type=' + type +';odds=' + oddsB.getValue() + ';stake=' + stakeB.getValue() +
                                ';currency=' + currencyB.getValue() + (cancelB != undefined ? ';cancel='  + cancelB.checked : '');
                        }
                    });
                }
                if (err == true)
                    return;
            });

            if (err == true)
                return;
            $('ReqSubmitButton'+ this.magicCode).disable();
            if (this.isInPlayMode()) {
                this.inPlayTimeoutVal = 8;
                this.sendSubmitRequest( req );
                $('MakeABetProgress' + this.magicCode).innerHTML = this.inPlayTimeoutVal + " Секунд";
                $('modalMakeABetPanel'+ this.magicCode).style.display = "block";
                $('modalMakeABetPanel'+ this.magicCode).style.height=$('requestField'+ this.magicCode).getHeight();
                this.updateMakeABetProgress();
            }
            else {
                this.sendSubmitRequest(req);
            }
        }
    },

    updateMakeABetProgress: function() {
        --this.inPlayTimeoutVal;
        $('MakeABetProgress'+ this.magicCode).innerHTML = this.inPlayTimeoutVal + ' Секунд';
        if (this.inPlayTimeoutVal <= 0) {
            return;
        }
        var __self = this;
        this.inPlayTimeout = window.setTimeout( function() { __self.updateMakeABetProgress(); }, 1000 );
    },

    cancelAllUnmatched: function() {
        if (this.options.loggedUser == false) {
            arube.ShowLogin();
            return;
        }
        $('CancelAllUnmatchedBetsButton'+ this.magicCode).disable();
        var __self = this;
        ajaxFacade.cancelAllUnmatchedRequests( this.arenaId, function(resp) {
            __self.refreshPlayField();
            __self.refreshMyBets();
        });
    },

    sendSubmitRequest: function(req) {
        var __self = this;
        ajaxFacade.arenaPlaceRequest( req, function(resp) {
            __self.submitResponseParser(resp);
        });
    },

    submitResponseParser: function(res) {
        var errors = false;
        $('ReqSubmitButton' + this.magicCode).enable();
        $('modalMakeABetPanel'+ this.magicCode).style.display = "none";
        var reqs = res.split('\n');
        for(var i = 0; i < reqs.length; i++) {
            if (reqs[i] != "") {
                var params = arube.Utils.parseServerResponse( reqs[i] );
                if (params["res"] == 1)  /* OK */
                    this.removeBet( params["betType"], params["oid"], true );
                else {
                    var elem = $( params["betType"] + "Status" + params["oid"] + this.magicCode );
                    elem.innerHTML = arube.Utils.decodeError( parseInt(params["res"]) );
                    errors = true;
                }
            }
        }
        if (!errors) {
            this.showBetTab( "myBets");
            this.refreshMyBets();
            this.hideBetTab('MakeABet');
        }
        if (typeof refreshLogonPanel == 'function') {
            refreshLogonPanel();
        }
        /*this.refreshPlayField();*/
    },

    /**  ------------------------------- MYBETS PARSING & DISPLAYING ----------------------------------**/


    /*
     * parses server response and calculates profit and loss for every outcome.
     */
    myBetsParser: function(resp) {
        this.myBetsBacks = new Hash();
        this.myBetsLays = new Hash();
        this.myCurrencies = new Hash();
        this.myUnmatchedBetsNumber = 0;

        var reqs = resp.split('\n');
        for(var i = 0; i < reqs.length; i++) {
            if (reqs[i] != "") {
                var params = arube.Utils.parseServerResponse( reqs[i] );
                if (params["type"] == "B") {
                    this.myBetsBacks.set( params['id'], params );
                }
                else
                if (params["type"] == "L") {
                    this.myBetsLays.set( params['id'], params );
                }
                this.myCurrencies.set(params['currency'], true );
                if (typeof params['status'] != 'undefined' && params['status'] == 1) {
                    ++this.myUnmatchedBetsNumber;
                }
            }
        }
        this.myBetsCalculateProfitAndLoss();
    },


    myBetsCalculateProfitAndLoss: function() {
        /* clean up some stuff */
        var __self = this;
        this.myBetsOutcomes.each(function(pair) {
            var pol = pair.value;
            if (typeof pol != 'undefined') {
                pol['persLiability'] = new Hash();
                pol['persProfitAndLoss'] = new Hash();
                pol['profitAndLoss'] = new Hash();
            }
            if ($('outcomeProfit' + pair.key + __self.magicCode) != null) {
                $('outcomeProfit' + pair.key + __self.magicCode).innerHTML = '';
                $('outcomeProfit' + pair.key + __self.magicCode).style.display="none";
            }
            if ($('outcomeLiability' + pair.key + __self.magicCode) != null) {
                $('outcomeLiability' + pair.key + __self.magicCode).innerHTML = '';
                $('outcomeLiability' + pair.key + __self.magicCode).style.display="none";
            }
            if ($('outcomeProfitNew' + pair.key + __self.magicCode) != null) {
                $('outcomeProfitNew' + pair.key + __self.magicCode).innerHTML = '';
                $('outcomeProfitNew' + pair.key + __self.magicCode).style.display="none";
            }
            if ($('outcomeLiabilityNew' + pair.key + __self.magicCode) != null) {
                $('outcomeLiabilityNew' + pair.key + __self.magicCode).innerHTML = '';
                $('outcomeLiabilityNew' + pair.key + __self.magicCode).style.display="none";
            }
        });

        this.myBetsConsiderProfitAndLoss( this.myBetsBacks );
        this.myBetsConsiderProfitAndLoss( this.myBetsLays );
        /* calculate real profit and loss considering other outcomes */
        this.calculateFinalProfitAndLoss('');

        var foundAtLeastOne = this.myBetsConsiderInputRequests();
        this.myBetsOutcomes.each(function(pair) {
            if ($('profitAndLossNew' + pair.key + __self.magicCode) != null) {
                $('profitAndLossNew' + pair.key + __self.magicCode).style.display = foundAtLeastOne == true ? '' : 'none';
            }
        });
        if (foundAtLeastOne) {
            this.calculateFinalProfitAndLoss('New');
        }
    },

    calculateFinalProfitAndLoss: function(postfix) {
        var __self = this;
        this.myBetsOutcomes.each(function(o1Pair) {
            var pol1 = o1Pair.value;
            if (typeof pol1 == 'undefined')
                __self.myBetsOutcomes.set( o1Pair.key, new Array() );
            pol1 = __self.myBetsOutcomes.get( o1Pair.key );
            __self.myCurrencies.each(function(curPair) {
                var pal = __self.myBetsGetPersonalProfitAndLoss(o1Pair.value, curPair.key );
                __self.myBetsOutcomes.each(function(o2Pair) {
                    var pol2 = o2Pair.value;
                    if (typeof pol2 != 'undefined' && o1Pair.key != o2Pair.key &&
                            typeof pol2['persProfitAndLoss'] != 'undefined' &&
                            typeof pol2['persProfitAndLoss'].get(curPair.key) != 'undefined')
                    {
                        pal -= __self.myBetsGetPersonalLiability( pol2, curPair.key );
                    }
                });
                if (typeof pol1['profitAndLoss'] == 'undefined')
                    pol1['profitAndLoss'] = new Hash();
                pol1['profitAndLoss'].set( curPair.key, pal );

                /* update playField */
                if (pal > 0 && $('outcomeProfit' + postfix+ o1Pair.key + __self.magicCode) != null) {
                    var prevHTML = $('outcomeProfit' + postfix + o1Pair.key + __self.magicCode).innerHTML;
                    $('outcomeProfit' + postfix + o1Pair.key + __self.magicCode).innerHTML += (prevHTML == '' ? '' : ', ') + arube.Utils.formatCurrency( pal, curPair.key );
                    $('outcomeProfit' + postfix + o1Pair.key + __self.magicCode).style.display="block";
                }
                else
                if (pal < 0 && $('outcomeLiability' + postfix+ o1Pair.key + __self.magicCode) != null) {
                    var prevHTML = $('outcomeLiability' + postfix + o1Pair.key + __self.magicCode).innerHTML;
                    $('outcomeLiability' + postfix + o1Pair.key + __self.magicCode).innerHTML += (prevHTML == '' ? '' : ', ') + arube.Utils.formatCurrency( pal, curPair.key );
                    $('outcomeLiability' + postfix + o1Pair.key + __self.magicCode).style.display="block";
                }
            });
        });
    },

    getProfitAndLoss: function(outcome, currency) {
        if (typeof this.myBetsOutcomes.get(outcome) == 'undefined' || typeof this.myBetsOutcomes.get(outcome)['profitAndLoss'] == 'undefined' ||
                typeof this.myBetsOutcomes.get(outcome)['profitAndLoss'].get(currency) == 'undefined')
        {
            return 0;
        }
        return this.myBetsOutcomes.get(outcome)['profitAndLoss'].get(currency);
    },

    getWorstLoss: function(currency) {
        var worstLoss = 0.0;
        var __self = this;
        this.myBetsOutcomes.each(function(pair) {
            worstLoss = Math.max( worstLoss, -__self.getProfitAndLoss(pair.key, currency));
        });
        return worstLoss;
    },

    getMaxProfit: function(currency) {
        var maxProfit = 0.0;
        var __self = this;
        this.myBetsOutcomes.each(function(pair) {
            maxProfit = Math.max( maxProfit, __self.getProfitAndLoss(pair.key, currency));
        });
        return maxProfit;
    },

    myBetsProduceView: function() {
        var prnt = $( "myBetsNew" + this.magicCode);
        if ($('myBetsBacks' + this.magicCode) != null)
            prnt.removeChild( $('myBetsBacks' + this.magicCode) );
        if ($('myBetsLays' + this.magicCode) != null)
            prnt.removeChild( $('myBetsLays' + this.magicCode) );
        prnt.appendChild( this.myBetsProduceBackView( this.myBetsBacks ) );
        prnt.appendChild( this.myBetsProduceLayView( this.myBetsLays ) );

        /* compile a liability line */
        var strL = '';
        var __self = this;
        this.myCurrencies.each(function(pair) {
            strL += arube.Utils.formatCurrency( __self.getWorstLoss(pair.key), pair.key ) + ", ";
        });
        /* remvoe comma at the end */
        if (strL.length > 2)
            strL = strL.substr( 0, strL.length-2 );
        $('myBetsTotalLiability' + this.magicCode).innerHTML = strL;

        var strP = '';
        this.myCurrencies.each(function(pair) {
            strP += arube.Utils.formatCurrency( __self.getMaxProfit(pair.key), pair.key ) + ", ";
        });
        /* remvoe comma at the end */
        if (strP.length > 2)
            strP = strP.substr( 0, strP.length-2 );
        $('myBetsTotalProfit' + this.magicCode).innerHTML = strP;

        if (this.myUnmatchedBetsNumber > 0) {
            $('CancelAllUnmatchedBetsBottom' + this.magicCode).style.display = "";
            $('CancelAllUnmatchedBetsButton' + this.magicCode).enable();
        }
    },

    myBetsProduceBackView: function(bets) {
        var newDiv = document.createElement('div');
        newDiv.setAttribute('class', 'backbet' );
        newDiv.setAttribute('id', 'myBetsBacks' + this.magicCode );
        var __self = this;
        if (bets.size() > 0) {

            var inner = '<table border="0" cellspacing="0" cellpadding="1" class="backbet"><tr>' +
               '<th width="160px" style="text-align:left;">За</th>' +
               '<th width="60px">Ваш коэф.</th>' +
               '<th width="100px">Ваша ставка</th>' +
               '<th width="40px">Ваша прибыль</th>' +
               '<th width="40px">Статус:</th></tr>';

            bets.each(function(pair) {
                var keyB = pair.key;
                var params = pair.value;

                inner += '<tr><td style="text-align:left;" valign="top">' +
                    (parseInt(params['status']) == 1 ? '<a href="javascript:" title="Отмена" onClick="' + __self.options.varName + '.removeBetRequest(' + params['id'] + '); return false;">X</a>\n' : '') +
                    '<span class="name">' + __self.outcomes.get(params['outcome']).name + '</span></td>' +
                    '<td><span class="input">' + params['odds'] + '</span></td>' +
                    '<td><span class="input">' + arube.Utils.formatCurrency( params['stake'], params['currency'] ) + '</span></td>' +
                    '<td><span class="input">' + arube.Utils.formatCurrency( __self.getProfit( 'B', params['odds'], params['stake'] ), params['currency'] ) + '</span></td>' +
                    '<td><span class="input">' + arube.Utils.betStatus[params['status']] + '</span></td>' +
                    '</tr>';
            });

            inner += '</table>';
            newDiv.innerHTML = inner;
        }
        return newDiv;
    },

    myBetsProduceLayView: function(bets) {
        var newDiv = document.createElement('div');
        newDiv.setAttribute('class', 'laybet' );
        newDiv.setAttribute('id', 'myBetsLays'  + this.magicCode );
        var __self = this;
        if (bets.size() > 0) {

            var inner = '<table border="0" cellspacing="0" cellpadding="1" class="laybet"><tr>' +
               '<th width="160px" style="text-align:left;">Против</th>' +
               '<th width="60px">Коэф. противника</th>' +
               '<th width="100px">Ставка противника</th>' +
               '<th width="40px">Ваша ответств.</th>' +
               '<th width="40px">Статус:</th></tr>';

            bets.each(function(pair) {
                var keyL = pair.key;
                var params = pair.value;

                inner += '<tr><td style="text-align:left;" valign="top">' +
                    (parseInt(params['status']) == 1 ? '<a href="javascript:" title="Отмена" onClick="' + __self.options.varName + '.removeBetRequest(' + params['id'] + '); return false;">X</a>\n' : '') +
                    '<span class="name">' + __self.outcomes.get(params['outcome']).name + '</span></td>' +
                    '<td><span class="input">' + params['odds'] + '</span></td>' +
                    '<td><span class="input">' + arube.Utils.formatCurrency( params['stake'], params['currency'] ) + '</span></td>' +
                    '<td><span class="input">' + arube.Utils.formatCurrency( __self.getLoss( 'L', params['odds'], params['stake'] ), params['currency'] ) + '</span></td>' +
                    '<td><span class="input">' + arube.Utils.betStatus[params['status']] + '</span></td>' +
                    '</tr>';
            });

            inner += '</table>';
            newDiv.innerHTML = inner;
        }
        return newDiv;
    },

    myBetsConsiderInputRequests: function() {
        var foundAtLeastOne = false;
        var __self = this;

        this.betStorage.each(function(formPair) {
            var bets = formPair.value;
            var type = formPair.key;
            if (typeof(bets) != 'undefined' && bets != null && bets.size() > 0) {
                if (type == 'B' || type == 'BL') {
                    bets.each(function(betPair) {
                        var keyB = betPair.key;
                        if (typeof keyB != 'undefined') {
                            var oddsB = $( type + 'Odds'+ keyB + __self.magicCode );
                            var stakeB = $(type + 'Stake'+keyB + __self.magicCode);
                            var currencyB = $(type + 'Currency'+keyB + __self.magicCode);
                            if (isNaN(parseFloat(oddsB.getValue())) || parseFloat(oddsB.getValue()) < 1.01 || parseFloat(oddsB.getValue()) > 1000.0) {
                                return false;
                            }
                            if (isNaN(parseFloat(stakeB.getValue())) || parseFloat(stakeB.getValue()) < __self.currencies.get(currencyB.getValue()).minBet) {
                                return false;
                            }
                            __self.myCurrencies.set(currencyB.getValue(), true );
                            __self.myBetsConsiderSingleRequest(keyB, true, currencyB.getValue(), oddsB.getValue(), stakeB.getValue() );
                            foundAtLeastOne = true;
                        }
                    });
                }
                else
                if (type == 'L') {
                    bets.each(function(betPair) {
                        var keyL = betPair.key;
                        if (typeof keyL != 'undefined') {
                            var oddsL = $('LayOdds'+keyL + __self.magicCode);
                            var stakeL = $('LayStake'+keyL + __self.magicCode);
                            var currencyL = $('LayCurrency'+keyL + __self.magicCode);
                            if (isNaN(parseFloat(oddsL.getValue())) || parseFloat(oddsL.getValue()) < 1.01 || parseFloat(oddsL.getValue()) > 1000.0) {
                                return false;
                            }
                            if (isNaN(parseFloat(stakeL.getValue())) || parseFloat(stakeL.getValue()) < __self.currencies.get(currencyL.getValue()).minBet) {
                                return false;
                            }
                            __self.myCurrencies.set(currencyL.getValue(), true );
                            __self.myBetsConsiderSingleRequest(keyL, false, currencyL.getValue(), oddsL.getValue(), stakeL.getValue() );
                            foundAtLeastOne = true;
                        }
                    });
                }
            }
        });
        return foundAtLeastOne;
    }

});


