/*
 * General Notes
 *
 * Process Statuses:
 *  C = Clear (nothing happening or scheduled)
 *  W = Waiting (waiting to see if we should get the count or wait more)
 *  P = Processing (getting the count)
 *  R = Currently Processing and we need to Reprocess after this processing is done.
 */
var timeToWait = 2; //seconds

function getNumberOfPlans(){
  /*
   *  Based on the user's choices on screen, this function gets the number of plans
   *  that would be returned.
   *  At the end, we either need to reprocess, or change the status.
   *  MJA - 20070105
   *  
   */
 
   /* Get the data from the form */
   var formQS;
   formQS = getFormData();
   var theURL;
   theURL = "planComparisonCount.aspx?filter=1&" + formQS;

   /* Call the page, AJAX Style that tells us the count */
   getHttpRequest("POST", theURL, true, handleResponse, formQS);
   /* Put the count in the right place on screen */
   
   /* Done processing -- start over if needed */
   var currentStatus;
   currentStatus = globalGetTextOfTextbox('hidProcessStatus');
   if(currentStatus == "R"){
     /* Reprocessing is needed so set the status to W (wait) and pretend somebody just changed a field */
     globalSetTextOfTextbox('hidProcessStatus', 'W');
     handleChange();
   }else{
     /* Done processing - use C (clear) for status) */
     globalSetTextOfTextbox('hidProcessStatus', 'C');
   }
}
function handleChange(){
  /*
   * When an item in the comparison charts is modified, this should be called.
   * If we are currently processing an event, it sets the status to R (Reprocess needed)
   * If not currently processing, it sets the status to W (waiting) and ups the event number.
   * and in five seconds calls processEventIfReady.
   */
   var currentStatus;
   var currentEventNumber;
   var nextEventNumber;

   currentStatus = globalGetTextOfTextbox('hidProcessStatus');
   currentEventNumber = globalGetTextOfTextbox('hidProcessEventNumber');

   if(currentStatus == "P"){
     /* We are currently processing and want to process again when we're done */
     globalSetTextOfTextbox('hidProcessStatus', 'R');
   }else{
     if(currentStatus != "R"){
       /* We aren't planning on reprocesssing, so set it up so we will process in 5 seconds */
       globalSetTextOfTextbox('hidProcessStatus', 'W');
       nextEventNumber = incrementNumber(currentEventNumber);
       //alert(nextEventNumber);
       globalSetTextOfTextbox('hidProcessEventNumber', nextEventNumber);
       
       globalSetTextOfDiv("spnMatchTop", "Updating...<BR>");
       globalSetTextOfDiv("spnMatchBottom", "Updating...<BR>");
   
       /* in five seconds, if nothing else has changed, get the count.  If something changes, the timer resets */
       var timer = setTimeout("processEventIfReady(" + nextEventNumber + ");", 1000 * timeToWait);
     }
   }
}
function incrementNumber(sNumber){
  /* Just parses the text and adds one to the number */
  var theNumber;
  theNumber = parseInt(sNumber);
  theNumber = theNumber + 1;
  return theNumber;
}
function processEventIfReady(eventNumber){
  /*
   * Checks to see if the passed in eventNumber is the one still in the hidden variable
   * -if it is, we need to set the status to P (processing) and run the process
   * MJA 20070105
   */
   var currentStatus;
   var currentEventNumber;
   
   currentStatus = globalGetTextOfTextbox('hidProcessStatus');
   currentEventNumber = globalGetTextOfTextbox('hidProcessEventNumber');
   
   /* If we aren't waiting, we don't need to do anything */
   if(currentStatus == "W"){
     if(currentEventNumber == eventNumber){
       /* only process if no events occurred after this one was scheduled */
       globalSetTextOfTextbox('hidProcessStatus', 'P');
       getNumberOfPlans();
     }
   }
}

function handleResponse(){
  /* 
   * Handles response and sets text for number of plans as returned 
   * MJA 20070105
   */
  if(request.readyState == 4){
    if(request.status == 200){
      var answer;
      answer = request.responseText;
      globalSetTextOfDiv("spnMatchTop", answer);
      answer = answer.replace('count', 'count2');
      globalSetTextOfDiv("spnMatchBottom", answer);
    }
  }
}
function doNothing(){
  return "";
}
function canISubmit(){
  if(document.getElementById){
    var theDiv;
    theDiv = document.getElementById("spnMatchBottom");
    if(theDiv){
      if(theDiv.innerText == "Updating..."){
        var timer = setTimeout("doNothing()", 3000);
        alert("Calculating");
      }
      if(theDiv.innerText == "0 Plans Match"){
        return false;
      }else{
        return true;
      }
    }
  }
  
}
function checkDivs(){
  //checks to see if collapseables should be open or closed.
    global_toggleVisibilityCheckbox('chkByFees', 'divByFees_detail');
    global_toggleVisibilityCheckbox('chkAdvisorSoldFees', 'advisorSoldFees_detail');
    global_toggleVisibilityCheckbox('chkByInvestmentManager', 'lstInvestmentManagers');
    global_toggleVisibilityCheckbox('chkByInvestmentOption', 'investmentOption_detail');
    global_toggleVisibilityCheckbox('chkByMaximumTotalContributions', 'maximumTotalContribution_detail');
    global_toggleVisibilityCheckbox('chkByMinimumInitialContribution', 'minimumInitialContribution_detail');
    global_toggleVisibilityCheckbox('chkByMinimumSubsequentContribution', 'minimumSubsequentContribution_detail');
    global_toggleVisibilityCheckbox('chkByOtherStateBenefit', 'divOtherStateBenefits_detail');
    global_toggleVisibilityCheckbox('chkByPlanType', 'divByPlanType_detail');
    global_toggleVisibilityCheckbox('chkByStateTaxBenefits', 'divByStateTaxBenefits_detail');
    global_toggleVisibilityCheckbox('chkDirectSoldFees', 'directSoldFees_detail');
    global_toggleVisibilityCheckbox('chkPrepaid', 'divPrepaid_detail');
    global_toggleVisibilityCheckbox('chkSavingsPlans', 'divSavingPlan_detail');
    global_toggleVisibilityCheckbox('chkEnrollmentFees','enrollmentFees_detail');
}
function pageOnLoad(){
  //checkDivs();
 var timer = setTimeout("checkDivs()", 1000); 
  

}

function checkboxIsChecked(psId){
  if(document.getElementById){
    var oCheckbox;
    oCheckbox = document.getElementById(psId);
    if(oCheckbox){
      if(oCheckbox.checked == true){
        return true;
      }else{
        return false;
      }
    }else{
      return false;
    }
  }else{
    return false;
  }
}
function getDropdownValue(psId){
  if(document.getElementById){
    var oDrp;
    oDrp = document.getElementById(psId);
    if(oDrp){
      return oDrp.value;
    }
  }
}
function getFormData(){
  /*
   * Goes through the elements in the form and makes a long query string type string 
   * MJA 20070105
   */
   var qs;
   //qs = "coming=soon";
    qs = "&state=" + getDropdownValue("drpStates");
   
   /* State */
   /* Plan Type */
   if(checkboxIsChecked("chkByPlanType")){
     var text = "&planType=1";
     if(checkboxIsChecked("chkSavingsPlans")){
       text += "&savings=1";
       if(checkboxIsChecked("chkDirectSold")){
         text += "&direct=1";
       }
       if(checkboxIsChecked("chkAdvisorSold")){
         text += "&advisor=1";
       }
     }
     if(checkboxIsChecked("chkPrepaid")){
       //Prepaid state box.
       text += "&prepaid=1";
       //TODO: dropdown
       text += "&prepaidState=" + getDropdownValue("drpPrepaid");
     }
     qs += text;
   }
   
   /* State tax benefits */
   if(checkboxIsChecked("chkByStateTaxBenefits")){
     var text = "&stateBenefits=1";
     if(checkboxIsChecked("chkDeductContributions")){
       text += "&deductContributions=1";
     }
     if(checkboxIsChecked("chkTaxDeferredEarnings")){
       text += "&taxDeferredEarnings=1";
     }
     if(checkboxIsChecked("chkTaxFreeWithdrawls")){
       text += "&taxFreeWithdrawls=1";
     }
     if(checkboxIsChecked("chkCreditForContributions")){
       text += "&taxCreditContributions=1";
     }
     qs += text;
   }
   /* Other state benefits */
   if(checkboxIsChecked("chkByOtherStateBenefit")){
     var text = "&otherBenefits=1";
     if(checkboxIsChecked("chkFinancialAidBenefits")){
       text += "&finaidBenefits=1";
     }
     if(checkboxIsChecked("chkStateGrants")){
       text += "&matchingGrants=1";
     }
     if(checkboxIsChecked("chkRewardsProgram")){
		   text += "&rewardPrograms=1";
		 }
     qs += text;
   }
   /* Fees */
   if(checkboxIsChecked("chkByFees")){
     var text = "&fees=1";
     if(checkboxIsChecked("chkDirectSoldFees")){
       //TODO get radio/slider value
       text += "&directFees=1";
       text += "&dfLow=" + globalGetTextOfTextbox('directSlider_lowerValue');
       text += "&dfHigh=" + globalGetTextOfTextbox('directSlider_hidValue');
     }
     if(checkboxIsChecked("chkAdvisorSoldFees")){
       text += "&advisorFees=1";
       //TODO get radio/slider value
       text += "&afLow=" + globalGetTextOfTextbox('advisorSlider_lowerValue');
       text += "&afHigh=" + globalGetTextOfTextbox('advisorSlider_hidValue');
     }
     if(checkboxIsChecked("chkEnrollmentFees")){
		   text += "&enrollmentFees=1";
		   text += "&efLow=" + globalGetTextOfTextbox('enrollmentFeeSlider_lowerValue');
		   text += "&efHigh=" + globalGetTextOfTextbox('enrollmentFeeSlider_hidValue');
		 }
     qs += text;
   }
   /* Inv Option type */
   if(checkboxIsChecked("chkByInvestmentOption")){
     var text = "&optionType=1";
     if(checkboxIsChecked("chkAgeBased")){
       text += "&agebased=1";
     }
     if(checkboxIsChecked("chkEquity")){
       text += "&equity=1";
     }
     if(checkboxIsChecked("chkFixedIncome")){
       text += "&fixedincome=1";
     }
     if(checkboxIsChecked("chkBlended")){
       text += "&blended=1";
     }
     if(checkboxIsChecked("chkGuaranteed")){
       text += "&guaranteed=1";
     }
     if(checkboxIsChecked("chkCapitalPreservation")){
       text += "&capitalPreservation=1";
     }
     qs += text;
   }
   /* minimum initial contribution */
   if(checkboxIsChecked("chkByMinimumInitialContribution")){
     var text = "&byMIC=1";
     
     if(checkboxIsChecked("rdoMICUpTo50")){
       text += "&MICHigh=50";
     }
     if(checkboxIsChecked("rdoMICUpTo250")){
       text += "&MICHigh=250";
     }
     if(checkboxIsChecked("rdoMICUpTo500")){
       text += "&MICHigh=500";
     }
     if(checkboxIsChecked("rdoMICUpTo1000")){
       text += "&MICHigh=1000";
     }
     qs += text;
   }
   /* minimum subsequent contribution */
   if(checkboxIsChecked("chkByMinimumSubsequentContribution")){
     var text = "&byMSC=1";
     if(checkboxIsChecked("rdoMSCUpTo50")){
       text += "&MSCHigh=50";
     }
     if(checkboxIsChecked("rdoMSCUpTo250")){
       text += "&MSCHigh=250";
     }
     if(checkboxIsChecked("rdoMSCUpTo500")){
       text += "&MSCHigh=500";
     }
     if(checkboxIsChecked("rdoMSCUpTo1000")){
       text += "&MSCHigh=1000";
     }
     qs += text;
   }
   /* maximum total contribution */
   if(checkboxIsChecked("chkByMaximumTotalContributions")){
     var text = "&byMTC=1";
         if(checkboxIsChecked("rdoMTCOver100k")){
       text += "&MTCLow=100000";
     }
     if(checkboxIsChecked("rdoMTCOver200k")){
       text += "&MTCLow=200000";
     }
     qs += text;
   }
   /* investment managers */
   if(checkboxIsChecked("chkByInvestmentManager")){
     var text = "&byMgr=1";
     //Invest mgrs.
     qs += text + "&mgrs=" + getInvestmentManagers();
   }
   
   return qs;
   
}
function getInvestmentManagers(){
/* Figures out which managers are checked and returns a comma separated list of their ids. */
  var controls;
  var mgrs = "";
  var first = true;
  
  controls = document.getElementsByTagName("input");
  for(i = 0; i<controls.length; i++){
    if(controls[i].type == "checkbox"){
      if(controls[i].id.indexOf("dgdIMs") > -1){
        if(controls[i].checked == true){
          /* Get the id of the investment mgr */
          var theId;
          theId = controls[i].id.substring(0, controls[i].id.lastIndexOf("_"));
          theId += "_hidIMid";
          theId += controls[i].id.substring(controls[i].id.length-1);
          
          var theHiddenOne;
          if(document.getElementById){
            theHiddenOne = document.getElementById(theId);
            if(theHiddenOne){
              if(first == true){
                first = false;
              }else{
                mgrs += ",";
              }
              mgrs += theHiddenOne.value;
            }
          }
        }
      }
    }
  }
  //alert(mgrs);
  return mgrs;
}
/* Specific to plan comparison by state: */
function pageOnLoadPCMState(){
  /* May need to fix checked checkboxes here */
  var timer = setTimeout('fixCheckboxes();redoSelected();', 300); 
}
function fixCheckboxes(){
  /* Determines if each state is checked and if it is makes sure its details are open */
  var controls;
  if(document.getElementById){
    controls = document.getElementsByTagName("input");
    for(var i=0; i<controls.length; i++){
      if(controls[i].type == "checkbox"){
        if(controls[i].id.indexOf("plan_") < 0){
          if(controls[i].id.indexOf("state_") > -1){
            global_toggleVisibilityCheckbox(controls[i].id, controls[i].id + "_detail");
          }
        }
      }
    }
  }
}

function redoSelected(testCheckAll){
  /* Determines which plans are checked on the compare by state page and puts them in a list */
  var controls;
  var text = "";
  var count = 0;
  var selectedPlans = "";
  var allSelected = true;
  var chkAll;
  
  if(document.getElementById){
    controls = document.getElementsByTagName("input");
    chkAll = document.getElementById("chkAll");
    
    for(var i=0; i<controls.length; i++){
      if(controls[i].type == "checkbox"){
        /* If it's a plan and it's checked - make sure the state is also checked */
        if(controls[i].id.indexOf("plan_") > -1){
          if(controls[i].checked == true){
            var theState;
            theState = document.getElementById(controls[i].id.substring(0, controls[i].id.indexOf("_plan")));
            if(theState.checked == true){
              count = count + 1;
              /* Get the plan name */
              var subtext = "<div class='selectedPlanName'>";
              subtext += globalGetTextOfTextbox(controls[i].id.substring(controls[i].id.indexOf("plan")) + "_name");
              subtext += "</div>";
              text += subtext;
            }//if(theState.checked == true){
          }else{
            allSelected = false;
          }//if(controls[i].checked == true){
        }//if(controls[i].id.indexOf("plan_") > -1){
      }//if(controls[i].type == "checkbox"){
    }//for(var i=0; i<controls.length; i++){
    if(count > 0){
      if(count == 1){
        selectedPlans = "1 plan is selected:";
      }else{
        selectedPlans = count + " plans are selected:";
      }
      globalButtonEnable("btnSubmit", 1)
    }else{
      text = "&nbsp;";
      selectedPlans = "No plans are selected.";
      globalButtonEnable("btnSubmit", -1)
    }
    globalSetTextOfDiv("selectedPlans", text);
    globalSetTextOfDiv("plansAreSelected", selectedPlans);
    if(testCheckAll == true){
        chkAll.checked = allSelected;
    }
  }//if(document.getElementById){
}
function checkAll(chkbox){
  if(chkbox){
      controls = document.getElementsByTagName("input");
      for(var i=0; i<controls.length; i++){
        if(controls[i].type == "checkbox"){
          controls[i].checked = chkbox.checked;
        }
      }
   
    }
    fixCheckboxes();
}
function clearAllPlans(){
  /* Clears all selected plans in the comparison */
  var controls;
 
  if(document.getElementById){
    controls = document.getElementsByTagName("input");
    for(var i=0; i<controls.length; i++){
      if(controls[i].type == "checkbox"){
        /* If it's a plan and it's checked - make sure the state is also checked */
        if(controls[i].id.indexOf("state_") > -1){
          controls[i].checked = false;
        }
      }
    }
  }
  redoSelected();
  fixCheckboxes();
}
function checkPlanTypes(){
  var advSold;
  var dirSold;
  var advFees;
  var dirFees;
  var advFeesDiv;
  var dirFeesDiv;
  
  if(document.getElementById){
    advSold = document.getElementById("chkAdvisorSold");
    dirSold = document.getElementById("chkDirectSold");
    advFees = document.getElementById("chkAdvisorSoldFees");
    dirFees = document.getElementById("chkDirectSoldFees");
    
    advFeesDiv = document.getElementById("advisorSoldFees_detail");
    dirFeesDiv = document.getElementById("directSoldFees_detail");
    
    advFees.disabled = false;
    dirFees.disabled = false;
    
    if(advSold.checked == dirSold.checked){
      advFees.disabled = false;
      dirFees.disabled = false;
    }else{
      if(advSold.checked){
        dirFees.disabled = true;
        dirFees.checked = false;
        dirFeesDiv.style.display = "none";
      }else{
        advFees.disabled = true;
        advFees.checked = false;
        advFeesDiv.style.display = "none";
      }
    }
  }
}