/*  South African Paye JavaScript library, version 0.1
 *  (c) 2009 Bryan Allott, http://bryanallott.net/
 *  South African PAYE is freely distributable under the terms of an MIT-style license.
 *--------------------------------------------------------------------------*/


var SARS2009 = {
  rebate: 8280,
  rebate65: 5040,
  threshold: 46000,
  threshold65: 74000,
  tables:  [[0.0, 0.0, 0.18],
            [122001, 21960,  0.25],
            [195001, 40210,  0.3],
            [270001, 62710,  0.35],
            [380001, 101210, 0.38],
            [490001, 143010, 0.4]]
}

var SARS2010 = {
    rebate: 9756,
    rebate65: 5400,
    threshold: 54200,
    threshold65: 84200,
    tables:  [[0.0, 0.0, 0.18],
                [132001, 23760,  0.25],
                [210001, 43260,  0.3],
                [290001, 67260,  0.35],
                [410001, 109260, 0.38],
                [525001, 152960, 0.4]]
}

var SARS2011 = {
    rebate: 10260,
    rebate65: 5675,
    threshold: 57000,
    threshold65: 88528,
    tables:  [[0.0, 0.0, 0.18],
                [140001, 25200,  0.25],
                [221001, 45450,  0.3],
                [305001, 70650,  0.35],
                [431001, 114750, 0.38],
                [552001, 160730, 0.4]]
}

var PayeCalculator = function(taxable_income, over65, is_monthly) {
      
  return {
    SARS: function() {
      return SARS2011;
    },
    annual_taxable_income: function() { 
      return is_monthly ? (taxable_income*12.0) : taxable_income;
    },
    monthly_taxable_income: function() {
      return is_monthly ? taxable_income : (taxable_income/12.0);
    },
    annual_tax: function() {
      if((over65 && (this.annual_taxable_income <= this.SARS().threshold65)) || 
         (this.annual_taxable_income() <= this.SARS().threshold)) {
        return 0.0;
      } 
      var idx = 0;
      for(var ii=this.SARS().tables.length-1;ii!=0;ii--) {
        if(this.SARS().tables[ii][0] < this.annual_taxable_income()) {
          idx = ii;
          break;
        }
      }
      var tax = 0.0;
      tax = this.SARS().tables[idx][1] + (this.SARS().tables[idx][2] * (this.annual_taxable_income() - this.SARS().tables[idx][0] - 1));
      tax = tax - this.SARS().rebate;
      if(over65) {
        tax = tax - this.SARS().rebate65;
      }
      if(tax < 0) {
        tax = 0;
      }
      return tax;
    },
    monthly_tax: function() {
      return (this.annual_tax()/12.0);
    }
  };
}
