function BattleVoteRequest(){
    this.host = 'http://' + window.location.hostname + '/';
    //alert('New battle vote request ' + this.host)
    this.totalMoney = null;
    this.voteCost = 5000;
}

BattleVoteRequest.prototype.sendRequest = sendRequest;
BattleVoteRequest.prototype.declineRequest = declineRequest;
BattleVoteRequest.prototype.updateLMViews = updateLMViews;
BattleVoteRequest.prototype.setTotalMoney = setTotalMoney;
function sendRequest(battleId, senderId, voteFor, message){
    var voteStatus = $.ajax({
        url: this.host + "ajax/battles/sendVoteRequest.php",
        async: false,
        type: "POST",
        data: "battleId=" + battleId + "&senderId=" + senderId + "&voteFor=" + voteFor + "&message=" + escape(message)
    
    }).responseText;
    if (voteStatus == 'Request sent.') {
        if (this.totalMoney) {
            this.totalMoney -= this.voteCost;
            this.updateLMViews();
        }
    }
    return voteStatus
}

function setTotalMoney(amt){
    if (!isNaN(amt)) {
        //alert('setting totla money to ' + amt)
        this.totalMoney = amt;
        this.updateLMViews();
    }
}

function updateLMViews(){
    //alert('Updating LM money total to ' + this.totalMoney);
    var tlm = this.totalMoney / 100;
    tlm += '';
    x = tlm.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    
    $('.lmTotalMoney').html(x1);
}

function declineRequest(battleId, senderId){
    var success = $.ajax({
        url: this.host + "ajax/battles/declineVoteRequest.php",
        async: false,
        type: "POST",
        data: "battleId=" + battleId + "&senderId=" + senderId
    }).responseText;
    if (success == 'true') {
        return true;
    }
    return false;
    
}

function limitMessageLength(){

    var text = $(this).val();
    if (text.length > 100) {
        $(this).val(text.substr(0, 100));
    }
}

$(document).ready(initVoteRequests);
function initVoteRequests(){
    $('.voterequestMessage').keypress(limitMessageLength)
}

var battleVoterequest = new BattleVoteRequest();
