var path="http://"+window.location.host+"/servlet/WarrantCalculator";

function loadUnderlying()
{
    $(function(){
       var dataString = {key:"-1"};
       $.get(path,dataString,function(data){
           var selectElement = $("#parent");
           $.each(data.underlying,function(index,optionData){
               var option = "<option value=\""+ optionData.stockCode + "\">"+optionData.ssn+"</option>";
               $(selectElement).append(option);
           });
           $("span#selectedWarrant").html("");
       },"json");
    });
}

function loadWarrant()
{
    $(function(){
        var dataString = {parent:$("#parent").val(),key:"0"};
        $.post(path,dataString,function(data){
           var selectElement = $("#warrant").empty();
           $.each(data.result,function(index,optionData){
               var option = "<option value=\""+ optionData.stockCode + "\">"+optionData.ssn+"</option>";
               $(selectElement).append(option);
           });
           var selectedValue = $("#parent").val();
           reset();
            $("#parent").val(selectedValue);
           getWarrantInfo();
       },"json");
    });
}

function reset()
{
    document.warrantCalculator.reset();
}

function getWarrantInfo()
{
    $(function(){
        var warrantCode = $("#warrant").val();
        var dataString = {warrant:warrantCode,key:"0"};
        $.post(path,dataString,
            function(data) {
                var display = data.stockCode + " "+data.symbol;
                $("input:disabled").val("");
                $("span#selectedWarrant").text(display);
                $("input#symbol").val(data.symbol);
                $("input#warrantType").val(data.warrantType);
                $("input#wType").val(data.wType);
                $("input#exerciseType").val(data.exerciseType);
                $("input#eType").val(data.eType);
                $("input#currentOptionPrice").val(data.currentOptionPrice);
                $("input#exercisePrice").val(data.exercisePrice);
                $("input#exerciseRatio").val(data.exerciseRatio);
                $("input#maturity").val(data.maturity);
                $("input#maturityDisplay").val(data.maturityDisplay);
                $("input#currentPrice").val(data.currentPrice);
                $("input#rate").val(new Number(data.rate).toFixed(2));
                $("input#dividend").val(new Number(data.dividend).toFixed(2));
                $("input#iv").val(new Number(data.iv).toFixed(2));
                $("input#issuer").val(data.issuer);
            },"json");
    });
}

function formatDecimal(field)
{
    var tmp = document.getElementById(field);
    if(tmp.value=="")
    {
        tmp.value = "0.00";
    }
    else if(!isNaN(tmp.value))
    {
        tmp.value = new Number(tmp.value).toFixed(2);
    }
}

function validateInput()
{
    var msg = "";
    var currentPrice = document.getElementById("currentPrice");
    var rate = document.getElementById("rate");
    var dividend = document.getElementById("dividend");
    var impliedVol = document.getElementById("iv");

    if(!validateNotEmpty(currentPrice.value))
    {
        msg += "Current Share Price is a required field.";
    }
    if(!validateNotEmpty(rate.value))
    {
        msg += "Interest Rate is a required field.";
    }
    if(!validateNotEmpty(dividend.value))
    {
        msg += "Dividend is a required field.";
    }
    if(!validateNotEmpty(impliedVol.value))
    {
        msg += "Implied Volatility is a required field.";
    }
    if(msg!="")
    {
        alert(msg);
        return false;
    }
    if(!validateNumeric(currentPrice.value))
    {
        msg += "Current Share Price must be numeric.";
    }
    if(!validateNumeric(rate.value))
    {
        msg += "Interest Rate must be numeric.";
    }
    if(!validateNumeric(dividend.value))
    {
        msg += "Dividend must be numeric.";
    }
    if(!validateNumeric(impliedVol.value))
    {
        msg += "Implied Volatility must be numeric.";
    }
    if(msg!="")
    {
        alert(msg);
        return false;
    }
    if(parseFloat(currentPrice.value)<=0)
    {
        msg += "Current Share Price cannot be zero or negative.";
    }
    var flt = parseFloat(rate.value);
    if(flt<0 || flt > 100)
    {
        msg += "Interest rate cannot be negative or greater than 100.";
    }
    if(parseFloat(dividend.value)<0)
    {
        msg += "Dividend cannot be negative.";
    }
    if(parseFloat(impliedVol.value)<0)
    {
        msg += "Implied Volatility cannot be negative.";
    }
    if(msg!="")
    {
        alert(msg);
        return false;
    }
    return true;
}

function  validateNumeric( strValue ) {
  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
  return objRegExp.test(strValue);
}

function validateNotEmpty( strValue ) {
    var strTemp = strValue;
    strTemp = trimAll(strTemp);
    return strTemp.length > 0;
}

function trimAll( strValue ) {
 var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }

   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}


$(function() {
    $("a#calculate").click(function() {
        if(!validateInput())
        {
            return false;
        }
        var dataString = {currentPrice: $("input#currentPrice").val(),
                          maturity: $("input#maturity").val(),
                          iv: $("input#iv").val(),
                          rate: $("input#rate").val(),
                          dividend: $("input#dividend").val(),
                          warrantType: $("input#warrantType").val(),
                          exerciseType: $("input#exerciseType").val(),
                          ratio: $("input#exerciseRatio").val(),
                          exercisePrice: $("input#exercisePrice").val(),
                          key: "1"};
        $.post(path,dataString,
             function(data) {
                $("input#result").val(data.result);
                $("input#delta").val(data.delta);
                $("input#gamma").val(data.gamma);
                $("input#theta").val(data.theta);
                $("input#vega").val(data.vega);
            },"json");
    });
});

$(function() {
   $("#warrant").bind('change',getWarrantInfo);
});

$(function()
{
    $("#parent").bind('change',loadWarrant);
});