/*
@author tomfmason@gmail.com

*/

var icm = {
   stacks:[],
   payouts:[],
   r:[],
   equities:{},
   hasError:false,
   errorString:"",
   getStacks:function(){
     s = $("input[name^='stack'][value!='']");
     for(var i=0; i<s.length;i++){
        if(!isNaN(s[i].value)){
           this.stacks[this.stacks.length] = parseFloat(s[i].value);
        } else {
           this.hasError = true;
           this.errorString += s[i].value + " is not a number <br />";
        }
     }
   },
   //place holder function for getting payouts
   getPayouts:function(){
     p = $("input[name^='payout'][value!='']");
     for(var i=0; i<p.length;i++){
        if(!isNaN(p[i].value)){
           this.payouts[this.payouts.length] = parseFloat(p[i].value);
        }else{
           this.hasError = true;
           this.errorString += p[i].value + " is not a number <br />";
        } 
     }
   },
   //prepare and get the equities for each stack
   prepare:function(){
      if(this.hasError){
         this.hasError = false;
         this.errorString = "";
         $('#error').hide();
      }
      this.getStacks();
      this.getPayouts();
      if(!this.hasError && this.stacks.length <= 10 && this.payouts.length <= 5){
         total = 0;
         for(var i=0;i<this.stacks.length;i++){
            total += this.stacks[i];
         }
         for(var i=0;i<this.stacks.length;i++){
            this.equities["stack" + i] = Math.round(this.getEquity(total, i,0) * 10000) / 10000;
         }
         this.displayResults();
      } else {
         $("#error").show().html(this.errorString);
      }
   },
   //do the actual calculation
   getEquity:function(total, player, depth){
      eq = this.stacks[player] / total * this.payouts[depth];      
      if(depth + 1 < this.payouts.length){
         for(var i=0;i<this.stacks.length;i++){
            if(i != player && this.stacks[i] > 0.0){
               this.r[i] = this.stacks[i];
               this.stacks[i] = 0.0;
               eq += this.getEquity((total - this.r[i]), player, (depth + 1)) * (this.r[i] / total);
               this.stacks[i] = this.r[i];
            }
         }
      }
      return eq;
   },
   //display results
   displayResults:function(){
      i=0;
      for(var stack in this.equities){
         $("span#eq" + (i+1)).text(this.equities[stack]);
         i++;
      }
      this.stacks = [];
      this.payouts = [];
      this.equities = {};
      this.r = [];
   }
}
