
var reboot = $('#reboot').attr('data-reboot');
var timeout = false; 
var audio = document.getElementById('audio'); 
audio.volume = '0.6';
var disabled = false; 

rebootRoulette(); 
refreshDate();

function getCookie(name) {
    var matches = document.cookie.match(new RegExp(
      "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
    ));
    return matches ? decodeURIComponent(matches[1]) : undefined;
}

function setCookie(name, value, options) {
    options = options || {};

    var expires = options.expires;

    if (typeof expires == "number" && expires) {
        var d = new Date();
        d.setTime(d.getTime() + expires * 1000);
        expires = options.expires = d;
    }
    if (expires && expires.toUTCString) {
        options.expires = expires.toUTCString();
    }

    value = encodeURIComponent(value);

    var updatedCookie = name + "=" + value;

    for (var propName in options) {
        updatedCookie += "; " + propName;
        var propValue = options[propName];
        if (propValue !== true) {
            updatedCookie += "=" + propValue;
        }
    }
    
    document.cookie = updatedCookie;
}

function deleteCookie(name) {
    setCookie(name, "", {
        expires: -1
    })
}


function betAction(num) {

    this.bet = Math.ceil($('#bet').attr('value')); 
    this.balance = Math.ceil($('#balance').text());
    
    if (num === 0) {
        this.bet = 0;
    }
    
    if (typeof(num) === 'number') {
        this.bet += num; 
    }
    
    if (num === 'x2') {
        this.bet *= 2;
    }
    
    if (num === 'max' || this.balance <= this.bet) {
        this.bet = $('#balance').text();
    }
    
    $('#bet').attr('value', this.bet)
}

function setAudio(e) {
    if (getCookie('audio') == '1') {
        e.setAttribute('class', 'flaticon-multimedia'); 
        setCookie('audio', '0');
        audio.pause();
        audio.currentTime = 0;
    } else {
        e.setAttribute('class', 'flaticon-multimedia-1'); 
        setCookie('audio', '1');
    }
}

function is_disabled() {
    if (reboot <= 3000 || reboot >= 48000) {
        return true; 
    }
    return false; 
}

function addBet(type) { 
    this.user = $('#content').attr('data-user');
    if (this.user == '0') {
        modalOpen('Авторизация', 'auth'); 
    }
    
    this.balance = Math.ceil($('#balance').text()); 
    this.bet = Math.ceil($('#bet').attr('value')); 
    
    if (is_disabled() || this.bet > this.balance) {
        return ;
    }
    
    $.ajax({
        method: "POST",
        url: "api.php",
        async: true,
        cache: false,
        dataType: 'json', 
        data: { type: type, bet: $('#bet').attr('value') }
    })
    .success(function(data) {
        if (data.status == 'success') {
            $('#balance').text(data.balance); 
        }
        
        if (data.status == 'error') {
            alert(data.msg)
        }
                
        if (data.bets) {
            updateBet(data.bets)
        }
    });
}

function pad(num) {
		return num > 9 ? num : '0' + num;
}

function rebootTime(sec) {
    secFloor = Math.floor(sec);
    secMilli = (sec - secFloor);
    
    return pad(secFloor) + ':' + pad(Math.round(secMilli * 100));
}

function rebootRoulette() {
    if (timeout !== false) {
        clearInterval(timeout);
        timeout = false; 
    }
    
    timeout = setInterval(function() {
        reboot -= 100; 
        isrf = reboot / 1000; 
        
        if (isrf >= 0 && isrf <= 45) {
            $('#reboot-info').text(rebootTime(reboot / 1000)); 
            $('#reboot').css({width: (reboot * 100 / 45000) + '%'});             
        }
        
        if (reboot <= 0) {
            clearInterval(timeout);
            timeout = false; 
            reboot = 0;
        }
    }, 100);
}

function roulette(position, clr) {
    $('#reboot-info').text(rebootTime(0));
    $('#reboot').css({width: '0%'});   
    
    $('#roulette').css({marginLeft: '-539px'});
    
    if (getCookie('audio') == '1') {
        audio.play();
    }
    
    $('#roulette').animate({
            marginLeft: '-=' + position + 'px',
        },
        7000,
        function() {
            $('#last-game img:first').remove();
            $('#last-game').append('<img src="/theme/img/' + clr + '.png" />'); 
            
            $('#reboot-info').text('Старт игры...'); 
            rebootRoulette();
            
            setTimeout(function() {
              $('.x-user > div').html(''); 
              $('#x-bet').attr('class', 'x-bet');
            }, 2000)
        }
    );    
}

function refreshDate() 
{
    $.ajax({
        url: 'api.php',
        async: true,
        cache: false,
        dataType: 'json',
        success: function(data) {
            logs = ''
            if (data.last) {
                reboot = data.last;
                
                if (timeout === false) {
                    rebootRoulette();
                }
            }
            
            if (data.win) {
                setTimeout(function() {
                    roulette(Math.floor(data.win), data.gamelast);
                }, reboot);
                
            }
            
            $('#cnt-users').html(data.counters['users']); 
            $('#cnt-online').html(data.counters['online']); 
            $('#cnt-tour').html(data.counters['tour']);
            
            if (data.last < 3000 || data.last > 46000)
                $('#x-bet').attr('class', 'x-bet disabled');
            else 
                $('#x-bet').attr('class', 'x-bet');
            
            if (data.balance !== "undefined" && data.last > 3000 && data.last <= 48000)
                $('#balance').html(data.balance);
            
            if (data.bets) {
                updateBet(data.bets)
            }
            
            refreshDate();
        }, 
        error: function(e, s) {
            setTimeout(function(){ refreshDate(); }, 1000); 
        }
    });
}

function updateBet(bets) {
    for (var key in bets) {
        for (var s in bets[key]['bet']) {
            if (!$('div').is('#us' + key + '-' + s)) {
                $('#sp' + s).prepend('<div class="bet-user" id="us' + key + '-' + s+'"><span><b id="bet' + key + '-' + s + '">' + bets[key]['bet'][s] + '</b> <i class="flaticon-coin"></i></span><img src="/files/photo/small/' + bets[key]['photo'] + '.jpg" /><a target="_blank" href="' + bets[key]['profile'] + '">' + bets[key]['first_name'] + '<span class="hidden-480"> ' + bets[key]['last_name'] + '</span></a></div>'); 
            } else {
                $('#bet' + key + '-' + s).text(bets[key]['bet'][s]); 
            }
        }
    }
}
