var price = 0;
var TBLCost = 0;
var FSBOCost = 175;
var FSBOMLSCost = 0;
var FSBOSave = 0;
var FSBOMLSSave = 0;
document.onkeypress = keyPress;

function SalePrice() {
    $("#SalePrice1").html(formatCurrency(price));
    $("#SalePrice2").html(formatCurrency(price));
    $("#SalePrice3").html(formatCurrency(price));
}

function TBLPay() {
    TBLCost = price * .06;
    $("#TBLPay").html(formatCurrency(TBLCost));
}
function FSBOPay() {
    $("#FSBOPay").html(formatCurrency(FSBOCost));
}
function FSBOMLSPay() {
    FSBOMLSCost = 495 + (price * .024);
    $("#FSBOMLSPay").html(formatCurrency(FSBOMLSCost));
}

function FSBOSavings() {
    FSBOSave = TBLCost - FSBOCost;
    $("#FSBOSavings").css("color", SavingsStyle(FSBOSave));
    $("#FSBOSavings").css("fontSize", SavingsFont(FSBOSave));
    $("#FSBOSavings").html(formatCurrency(FSBOSave));
}

function FSBOMLSSavings() {
    FSBOMLSSave = TBLCost - FSBOMLSCost;
    $("#FSBOMLSSavings").css("color", SavingsStyle(FSBOMLSSave));
    $("#FSBOMLSSavings").css("fontSize", SavingsFont(FSBOMLSSave));
    $("#FSBOMLSSavings").html(formatCurrency(FSBOMLSSave));
}

function SavingsStyle(savings) {
    if( savings < 0 )
      return "red";
    else if( savings > 0 )
      return "green";
    else
      return "black";
}

function SavingsFont(savings) {
    if( savings < 0 )
      return "10pt";
    else if( savings > 0 )
      return "12pt";
    else
      return "8pt";
}

function CalculateSavings() {
    price = $("#txtSalePrice").val().replace(",","");
    
    if ( price == "" )
      price = 0;
    
    if( price != 0 ) {
        $("#savingsTable").css("display", "inline");
        SalePrice();
        TBLPay();
        FSBOPay();
        FSBOMLSPay();
        FSBOSavings();
        FSBOMLSSavings();
    }
    else {
        $("#savingsTable").css("display", "none");
    }
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    if( cents != "00" )
      return (((sign)?'':'-') + '$' + num + '.' + cents);
    else
      return (((sign)?'':'-') + '$' + num);
}

// capture key press
function keyPress(e) {
    var key = e ? e.which : window.event.keyCode;
    if( key == 13) {
      CalculateSavings();
      return false;
    }
    else
        return true;
}
