// Javascript to hook into the controls on the result page and provide dynamic enhancements
// such as hiding invalid combinations of options

function handleMonthlyRadioButton(evt)
{
  toggleTermBond($(evt.target),false);
}

function handleLumpSumRadioButton(evt)
{
    toggleTermBond($(evt.target), true);
}

function toggleTermBond(radioBtn, show) {
    var chkbox = $("[id$='cbTermOrBond']");
    if (chkbox.length > 0) {
        var label = $("[for$='" + chkbox.attr('id') + "']");
        var tr = label.parent().parent();

        if (label.length > 0) {
            if (show) {
                label.show();
                if (tr.length > 0) {
                    tr.show();
                }
                chkbox.removeAttr('disabled');
                chkbox.show();

                var termChkbox = $("[id$='cbTermOrBond']");
                showTermOrBondOptions(termChkbox);

            } else {
                label.hide();
                if (tr.length > 0) {
                    tr.hide();
                }
                chkbox.attr('disabled','disabled');
                chkbox.hide();

                var panel = $("[id$='panelTermOptions']"); 
                if (panel.length > 0) {
                    panel.hide();
                }
            }
        }
    }
}

function handleNoticeCheckbox(evt)
{
  showNoticeOptions($(evt.target));
}

function showNoticeOptions(chkbox) {

    if (chkbox.attr('checked')) {
        $("[id$='panelNoticeOptions']").show();
    } else {
        $("[id$='panelNoticeOptions']").hide();
    }
}

function handleTermOrBondCheckbox(evt)
{
  showTermOrBondOptions($(evt.target));
}

function showTermOrBondOptions(chkbox) {

    if (chkbox.attr('checked')) {
        $("[id$='panelTermOptions']").show();
    } else {
        $("[id$='panelTermOptions']").hide();
    }
}

function handleSortChanged(evt) {
    $("[id$='btnRefresh']").trigger('click');
}


function hookupSearchEnhancements(evt)
{
  initControls();
  addSearchControlHandlers();
  
  $('div.InvisibilityDivision').each(
    function (i)
    {
      $(this).show();
    }
  );
  
  $('p.SortList').each(
  function (i)
  {
    $(this).show();
  }
  );
}

function initControls()
{
  var radioBtn;
  var chkbox;

  radioBtn = $("[id$='rbLumpSum']");
  toggleTermBond(radioBtn, radioBtn.attr('checked'));
  showNoticeOptions($("[id$='cbNotice']"));
  showTermOrBondOptions($("[id$='cbTermOrBond']"));
}

function addSearchControlHandlers() {

    $("[id$='rbMonthly']").bind('click', handleMonthlyRadioButton);
    $("[id$='rbLumpSum']").bind('click', handleLumpSumRadioButton);
    $("[id$='cbNotice']").bind('click', handleNoticeCheckbox);
    $("[id$='cbTermOrBond']").bind('click', handleTermOrBondCheckbox);
    $("[id$='drpSorting']").bind('change', handleSortChanged);
}


$(document).ready(hookupSearchEnhancements);
