  var flagValidZip = false;
  var flagAllValid = false;
  
  var flagAjaxZip = false;
  
  var flagFirstTime = false;
  
  var zipSavedState = '';
  var amountSavedState = '';
  var radioButtonSavedState = '';
  
  var filter_term = '';
  var filter_type = '';
  
  var emptyZipFilter = false;
  
  function getRadioSelected () 
  {
    var valueSelected = '';
    for (i=0; i < 3; i++) {
      if (document.getElementById('cdRates').cdoption[i].checked) {
        valueSelected = document.getElementById('cdRates').cdoption[i].value;
      }
    }
    return valueSelected;
  }
  
  function disableAllRadioBox()
  {
    $('#radio_variable').attr ( 'disabled', true);
    $('#radio_variable').attr ('checked', false);
    
    $('#radio_fixed').attr ( 'disabled', true);
    $('#radio_fixed').attr ('checked', false);
    
    $('#radio_standard').attr ( 'disabled', true);
    $('#radio_standard').attr ('checked', false);
  }
  
  function getComboBox ()
  {
    var cd_amount =$('#cd_amount').val().replace('$','').replace(',','');
    
    var myNum = new Number(cd_amount);
    myNum = myNum.toFixed(0);
    $.ajax({
        type: "POST",
        url: "/widgets/getcdradiobox",
        data: "zipcode="+ $('#cd_zipcode').val().substr(0, 3) + "&product_id=" + cd_product_id + "&amount="+myNum,
        success: function(html){
        
          var json = eval('(' + html + ')');
          
          disableAllRadioBox();
          
          if( json.standard > '0' )
          {
            $('#radio_standard').attr ( 'disabled', false);
          }
          else
          {
            $('#radio_standard').attr ( 'disabled', true);
          }
          
          if( json.fixed > '0' )
          {
            $('#radio_fixed').attr ( 'disabled', false);
          }
          else
          {
            $('#radio_fixed').attr ( 'disabled', true);
          }
          
          if( json.variable > '0' )
          {
            $('#radio_variable').attr ( 'disabled', false);
          }
          else
          {
            $('#radio_variable').attr ( 'disabled', true);
          }
          
          // set default radio button
          if ( json.standard > '0' )
          {
            $('#radio_standard').attr ('checked', true);
            setRadioBox( json.standard, json.fixed, json.variable );
            getSelectBox ();
            flagAllValid = true;
          }
          else
          {
            if( json.fixed > '0' )
            {
              $('#radio_fixed').attr ('checked', true);
              setRadioBox( json.standard, json.fixed, json.variable );
              getSelectBox ();
              flagAllValid = true;
            }
            else
            {
              if( json.variable > '0' )
              {
                $('#radio_variable').attr ('checked', true);
                $("#error_message").html('');
                flagAllValid = true;
                setRadioBox( json.standard, json.fixed, json.variable );
                getSelectBox ();
              }
              else
              {
                flagAllValid = false;
                $("#div_select_term").html("<select class='cd_pr_select_term'><option>-</options></select>");
                $("#error_message").html('<ul style="list-style-type: disc;" ><li> Product Not Available for that amount.</li></ul>');
                amountSavedState = '';
              }
            }
          }
          
          
        }
      });
  }
  
  function getSelectBox ()
  {
    var cd_amount =$('#cd_amount').val().replace('$','').replace(',','');
    var myNum = new Number(cd_amount);
    myNum = myNum.toFixed(0);
    
    if ( zipSavedState != $('#cd_zipcode').val().substr(0, 3) ||  amountSavedState != myNum || radioButtonSavedState != getRadioSelected() )
    {
      zipSavedState = $('#cd_zipcode').val().substr(0, 3);
      amountSavedState = myNum;
      radioButtonSavedState = getRadioSelected();
      
      $.ajax({
          type: "POST",
          url: "/widgets/getcdselectbox",
          data: "zipcode="+ $('#cd_zipcode').val().substr(0, 3)+"&product_id="+cd_product_id+"&amount="+myNum+"&cd_ira="+getRadioSelected(),
          success: function(html){
            $("#div_select_term").html(html);
            setComboBox();
          }
        });
    }
  }
  
  function getValidateZip ()
  {
    var cd_amount =$('#cd_amount').val().replace('$','').replace(',','');
    var myNum = new Number(cd_amount);
    myNum = myNum.toFixed(0);
    
    if ( zipSavedState != $('#cd_zipcode').val().substr(0, 3) || amountSavedState != myNum  )
    {
      $.ajax({
          type: "POST",
          url: "/widgets/validatecdzip",
          data: "zipcode="+ $('#cd_zipcode').val().substr(0, 3)+"&product_id="+cd_product_id,
          success: function(html){
            var json = eval('(' + html + ')');
            if ( json.count > 0 )
            {
              flagValidZip = true;
              $("#error_message").html('');
              amountcheck();
            }
            else
            {
              flagValidZip = false;
              flagAllValid = false;
              zipSavedState = '';
              $("#div_select_term").html("<select class='cd_pr_select_term'><option>-</options></select>");
              $("#error_message").html('<ul style="list-style-type: disc;" ><li> Product Not Available for the ZIP Code entered.</li></ul>');
              disableAllRadioBox();
            }
          }
        });
    }
    else
    {
      amountcheck();
    }
      
  }
  
  
  function zipfocus()
  {
     
    if ( $("#cd_zipcode").val() == 'Zip Code' ||  $("#cd_zipcode").val() == 'Invalid' )
    {
      $("#cd_zipcode").attr('maxlength','5');
      $("#cd_zipcode").val('');
      $("#cd_zipcode").css('color','#666666');
    }
  }
  
  function amountfocus()
  {
     
    if ( $("#cd_amount").val() == 'Deposit Amount' ||  $("#cd_amount").val() == 'Invalid')
    {
       $("#cd_amount").val('');
       $("#cd_amount").css('color','#666666');
    }
  }
  
  
  function zipcodeBlur()
  {
      flagAjaxZip = false;
    if ( $("#cd_zipcode").val() != 'Zip Code' )
    {
      if ($("#cd_zipcode").val() == '')
      {
        $("#cd_zipcode").attr('maxlength','25');
        $("#cd_zipcode").val('Zip Code');
        $("#div_select_term").html("<select class='cd_pr_select_term'><option>-</options></select>");
        flagAllValid = false;
                flagValidZip = false;
                zipSavedState = '';
                $("#cd_zipcode").blur();
                disableAllRadioBox();
      }
      else
      {
                var re  = /(^\d{5}$)/;
                if (!$("#cd_zipcode").val().match(re)) 
                {
                    if (emptyZipFilter == true)
                    {
                      $("#cd_zipcode").attr('maxlength','25');
                        $("#cd_zipcode").val('Zip Code');
            $("#div_select_term").html("<select class='cd_pr_select_term'><option>-</options></select>");
            flagAllValid = false;
            flagValidZip = false;
            zipSavedState = '';
            disableAllRadioBox();
            emptyZipFilter = false;
          }
          else
          {
              $("#cd_zipcode").attr('maxlength','25');
                        $("#cd_zipcode").css('color','red');
                        $("#cd_zipcode").val('Invalid');
                        $("#div_select_term").html("<select class='cd_pr_select_term'><option>-</options></select>");
                        flagAllValid = false;
                        flagValidZip = false;
                        zipSavedState = '';
                        disableAllRadioBox();
          }
                }
                else
                {
            $.ajax({
                      type: "POST",
                      url: "/widgets/zipExist",
                      data: "zipcode="+ $('#cd_zipcode').val(),
                      success: function(html){
                          var json = eval('(' + html + ')');
                          if ( json.count > 0 )
                          {
                              getValidateZip ();
                          }
                          else
                          {
                              $("#cd_zipcode").attr('maxlength','25');
                              $("#cd_zipcode").css('color','red');
                              $("#cd_zipcode").val('Invalid');
                              $("#div_select_term").html("<select class='cd_pr_select_term'><option>-</options></select>");
                              flagAllValid = false;
                              flagValidZip = false;
                              zipSavedState = '';
                              $("#cd_zipcode").blur();
                              disableAllRadioBox();
                          }
                      }
                  });
                  flagAjaxZip = true;
                }
      }
    }
  }
  
  function amountBlur()
  {
        if (flagAjaxZip)
        {
      if ( $("#cd_amount").val() != 'Deposit Amount' )
      {
        if ($("#cd_amount").val() == '')
        {
          $("#cd_amount").val('Deposit Amount');
          $("#div_select_term").html("<select class='cd_pr_select_term'><option>-</options></select>");
          flagAllValid = false;
                  amountSavedState = '';
                  disableAllRadioBox();
        }
        else
        {
          
          amountcheck();
        }
      }
    }
  }
  
  function amountcheck()
  {
    var cd_amount =$('#cd_amount').val().replace('$','').replace(',','');
    var myNum = new Number(cd_amount);
    myNum = myNum.toFixed(0);
    
    if ( zipSavedState != $('#cd_zipcode').val().substr(0, 3) || amountSavedState != myNum  )
    {
      var re = new RegExp("^\\$?[0]*(([1-9]{1}[0-9]{0,2}(,[0-9]{3}){1,2})|([1-9]{1}[0-9]{0,8}))(\\.[0-9]{2})?$");
          
          if ($("#cd_amount").val() != '' && $("#cd_amount").val() != 'Deposit Amount')
      {
            if (!$("#cd_amount").val().match(re)) 
            {
          $("#cd_amount").css('color','red');
          $("#cd_amount").val('Invalid');
          $("#div_select_term").html("<select class='cd_pr_select_term'><option>-</options></select>");
          flagAllValid = false;
          amountSavedState = '';
          $("#cd_amount").blur();
          disableAllRadioBox();
        }
        else
        {
          if (flagValidZip) 
          {
            $("#error_message").html('');
            getComboBox();
          }
        }
      }
    }
  }
  
  
  function callResponsePage()
  {
      var cd_amount =$('#cd_amount').val().replace('$','').replace(',','');
        var myNum = new Number(cd_amount);
        myNum = myNum.toFixed(0);
        
    $.ajax({
        type: "POST",
        url: "/widgets/cdsinfos",
        data: "zipcode="+ $('#cd_zipcode').val()+"&cd_term="+$('#pricerates_ppicker_inputs_select').val()+"&cd_type="+getRadioSelected()+"&amount="+myNum+"&product_id="+cd_product_id+"&cd_rate_id="+cd_rate_id+"&first_time="+flagFirstTime,
        success: function(html){
          $('#nationalPriceRates').css('display','none');
          $('#cdpriceratesresult').html(html);
          vtyCalculation();
        }
      });
  }
  
  function goAction()
  {
    zipcodeBlur();
    if (flagAjaxZip)
    {
      if(flagAllValid && flagValidZip)
      {
        callResponsePage();
      }
    }
  }
  
  function vtyCalculation()
  {
        if (flagFirstTime == false)
        {
      var cd_amount =$('#cd_amount').val().replace('$','').replace(',','');
      
      var myNum = new Number(cd_amount);
      myNum = myNum.toFixed(0);
      $.ajax({
          type: "POST",
          url: "/widgets/calculatecdvty",
          data: {
            cd_term: $('#pricerates_ppicker_inputs_select').val(),
            amount: myNum,
            product_id: cd_product_id,
            cd_rate_id: cd_rate_id,
            zip_code: $('#cd_zipcode').val(),
            cd_type: getRadioSelected()
          },
          success: function(html){
            var json = eval('(' + html + ')');
            
            var div_html = '';
                              
            if( json.result == 'OK' )
            {
              cd_vty = makeVtyDisplay(json.vty);
              
              if ($('#personal_value').length != 0)
              {
                div_html = '<div class="vty-tt">';
                
                if (json.vty >= 0 )
                {
                  div_html += 'Personal Value <a rel="#pv" class="pt-tt" rel="#pv" href="#" >?</a>';
                }
                else
                {
                  div_html += 'Personal Cost <a rel="#pv" class="pt-tt" rel="#pv" href="#" >?</a>';
                }
                
                div_html += '</div> <h4 class="value"><span>$</span>' + cd_vty + '</h4>';
                
                $('#personal_value').html(div_html);              
              }
              else
              {
              
                if (json.vty >= 0 )
                {
                  div_html = '<div id="personal_value" class="vty">';
                }
                else
                {
                  div_html = '<div id="personal_value" class="cty">';
                }
                
                div_html += '<div class="vty-tt">';
                
                if (json.vty >= 0 )
                {
                  div_html += 'Personal Value <a rel="#pv" class="pt-tt" rel="#pv" href="#" >?</a>';
                }
                else
                {
                  div_html += 'Personal Cost <a rel="#pv" class="pt-tt" rel="#pv" href="#" >?</a>';
                }
                
                div_html += '</div> <h4 class="value"><span>$</span>' + cd_vty + '</h4></div>'
                var old_html = $('#div_to_place_vty').html();
                $('#div_to_place_vty').html(div_html + old_html);
              }
            }
            activeToolTip();
          }
        });
      }
      else
      {
                flagFirstTime = false;
      }
  }
    
  function makeVtyDisplay(vty) {
    // VTY display should be either an abbreviated form or rounded integer
    if (Math.abs(vty) >= 10000) {
      return Number(vty/1000).toFixed(1).replace('.0', '') + 'k';
    } else {
      return Math.abs(Math.round(vty)).toString();
    }
  }
  
  
  function useFilter ( zipcode, amount, term, type ) 
  {
        $('#cd_zipcode').val(zipcode);
      $("#cd_zipcode").attr('maxlength','5');
     
      $("#cd_amount").val(amount);
     
      filter_type = type;
     
      filter_term = term;
      
      if (cd_rate_id != '' )
        {
         flagFirstTime = true;
        }
        else
        {
            flagFirstTime = false;
        }
        
        if(zipcode == 0 || zipcode == '' )
        {
            emptyZipFilter = true;
        }
               
        zipcodeBlur();
        
  }
  
  function setRadioBox( standard, fixed, variable )
  {
     var radioBoxOK = false;
     if ( has_filter && filter_type != '')
        {
            if (filter_type == 'standard' && standard > 0 )
            {
                $('#radio_standard').attr ('checked', true);
                radioBoxOK = true;
            }
            else if (filter_type == 'fixed' && fixed > 0)
            {
                $('#radio_fixed').attr ('checked', true);
                radioBoxOK = true;
            }
            else if (filter_type == 'variable' && variable> 0)
            {
                $('#radio_variable').attr ('checked', true);
                radioBoxOK = true;
            }
            
            filter_type = '';
            if (!radioBoxOK)
            {
                has_filter = false;
            }
        }
  }
  
  function setComboBox ()
  {
      if ( has_filter && filter_term != '')
        {
            $('#pricerates_ppicker_inputs_select').val(filter_term);
            filter_term = '';
            callResponsePage();
        }
  }
  
  function keyPressHandler(e) {
      var kC  = (window.event) ?    // MSIE or Firefox?
                 event.keyCode : e.keyCode;
      var Esc = (window.event) ?   
                27 : e.DOM_VK_ESCAPE // MSIE : Firefox
      if(kC==Esc)
         $("#cd_zipcode").blur();
   }
  
  