/* 0: free
   1: basic
   2: pro
   3: enterprise
*/
function calculateMonthly(pkg, operators) {
    var base;
    switch (pkg) {
        case 0: base = 0; break;
        case 1: base = 9; break;
        case 2: base = 29; break;
        case 3: base = 49; break;
    }
    /*
    * NOTE: replicated in Billing.java
    *  10% discount for 3-9 users
    * 15% discount for 10-24 users
    * 20% discount for 25+ users
    */
    var discount = 0;
    if (operators >= 25) {
        discount = 20;
    } else if (operators >= 10) {
        discount = 15;
    } else if (operators >= 3) {
        discount = 10;
    }
    return Math.round((base * operators) * ((100 - discount) / 100));
}

function updateOps(operators) {
    operators = parseInt(operators);
    var empty = !(operators + "").match(/^\d+$/);
    for (var i = 0; i <= 3;i++) {
        var el = document.getElementById("total_" + i);
        if (el == null) continue;
        if (empty) {
            el.innerHTML = "";
        } else {
            if (i == 0) {
                if (operators > 1) {
                    el.innerHTML = "Unavailable";
                } else {
                    el.innerHTML = "Free";
                }
            } else {
                var amount = calculateMonthly(i, operators);
                el.innerHTML = "<b>US$ " + formatAmount(amount) + "</b>";
            }
        }
    }
}

function formatAmount(amount) {
    // Round to two decimal places
//    amount=Math.round(amount*100)/100  //returns 28.45
    amount=Math.round(amount); //returns 28.45
    return amount;
//    amount = "" + amount;
//    if (amount.indexOf(".") == -1) {
//        return amount + ".00";
//    } else if (amount.match(/.*\.\d$/)) {
//        return amount + "0";
//    } else {
//        return amount;
//    }
}

$(document).ready(function() {
    // Set tooltips
    $('.term').qtip({
      /*
      content: {
           text: 'Canned messages make it easy to reply with stock answers to common questions.'
       },
       */
       show: 'mouseover',
       hide: 'mouseout',
        style: {
           fontSize:'12.8px',
            lineHeight: '120%',
           border: {
              width: 5,
              radius: 10
           },
           padding: 10,
           tip: true, // Give it a speech bubble tip with automatic corner detection
           name: 'cream' // Style it according to the preset 'cream' style
        },
        position: {
           corner: {
              tooltip: 'rightMiddle', // Use the corner...
              target: 'leftMiddle' // ...and opposite corner
           }
        }
    });
    var opsEl = document.getElementById("operators");
    if (opsEl == null) return;
    updateOps(opsEl.value);    
});