/// <reference path="vswd-ext_2.1.js" />

ibrSection = {
   // public variables
   form: null,
   nslp_image: {
      src: '../ibr/img/incomeBased_nslp.gif',
      usemap: '',
      width: 620,
      height: 186
   },
   eqf_image: {
      src: '../ibr/img/IBRcalc.jpg',
      usemap: '#EdquestHome',
      width: 620,
      height: 163
   },
   imageHTML: '<img id="topper" src="../ibr/img/IBRcalc.jpg" usemap="#EdquestHome" width="620" height="163" >',
   style: 'background-color: #DBE6D3; padding:12px',

   setImage: function() {
      var EQFIcon = true;
      var siteURL = Ext.getDom(document).URL.toLowerCase()
      var sitebegin = siteURL.indexOf("site=");
      if (sitebegin > -1) {
         if (siteURL.substring(sitebegin + 5) == 'nslp') {
            EQFIcon = false;
            this.imageHTML = buildImage(this.nslp_image);
            this.style = 'padding:12px';
            Ext.getDom('footer').innerHTML = 'used with permission from EducationQuest Foundation &#169; 2009';
         }
//         else {
//            this.imageHTML = buildImage(this.eqf_image);
//         };
      }
      addFavIcon(EQFIcon);
   },
   
   init: function() {
      this.setImage();

      // private variables
      var stateData = [
		   ['AL', 'Alaska'],
		   ['HI', 'Hawaii'],
		   ['US', 'Other']
	   ];

      this.form = new Ext.FormPanel({
         bodyBorder: false,
         border: false,
         frame: false,
         id: 'loanForm',
         labelAlign: 'right',
         labelWidth: 155,
         width: 621,
         monitorValid: true,
         bodyStyle: this.style,
         buttonAlign: 'right',
         buttons: [{
            text: 'Calculate',
            handler: function() {
               var myFormPanel = Ext.getCmp('loanForm');
               var myForm = myFormPanel.getForm();

               if (myForm.isValid()) {
                  myForm.submit({
                     url: 'IBRcalc.asp',
                     success: function(form, action) {
                        // possibly add table dynamically using javascript;  http://extjs.com/forum/showthread.php?t=20011&highlight=domhelper+create+table
                        var pfhObj = {
                           pfhtitle: 'Income-based',
                           pfhterm: '',
                           pfhrate: '',
                           pfhpayment: '0',
                           pfhpmt: -1,
                           pfhloanamt: '',
                           pfhnumofmonths: '',
                           pfhremain: ''
                        };
                        //same object only done differently
                        pfhObj['pfhtotint'] = '';
                        pfhObj['pfhtotpay'] = '';
                        pfhObj['pfhremainpayment'] = '';

                        //dynamically create table
                        var table1 = Ext.get('levelTable');
                        if (!table1) {
                           Ext.DomHelper.append('repayDiv', {
                              tag: 'table',
                              id: 'levelTable',
                              cls: 'repayTable',
                              children: [{
                                 tag: 'thead',
                                 id: 'table-head',
                                 children: [{
                                    tag: 'tr',
                                    children: [{
                                       tag: 'td', cls: 'heading standard colhead',
                                       colspan: 2,
                                       html: '<div >Level</div>Repayment'
                                    }]
                                 }]
                              }, {
                                 tag: 'tbody',
                                 id: 'table-body',
                                 children: [{
                                    tag: 'tr',
                                    children: [{
                                       tag: 'td', cls: 'separator standard',
                                       colspan: 2,
                                       html: '&nbsp;'
                                    }]
                                 }, {
                                    tag: 'tr',
                                    children: [{
                                       id: 'term',
                                       tag: 'td', cls: 'standard',
                                       colspan: 2,
                                       html: '&nbsp;'
                                    }]
                                 }, {
                                    tag: 'tr',
                                    children: [{
                                       id: 'loanamt',
                                       tag: 'td', cls: 'standard',
                                       colspan: 2,
                                       html: '&nbsp;'
                                    }]
                                 }, {
                                    tag: 'tr',
                                    children: [{
                                       id: 'totint',
                                       tag: 'td', cls: 'standard',
                                       colspan: 2,
                                       html: '&nbsp;'
                                    }]
                                 }, {
                                    tag: 'tr',
                                    children: [{
                                       id: 'totpay',
                                       tag: 'td', cls: 'standard',
                                       colspan: 2,
                                       html: '&nbsp;'
                                    }]
                                 }, {
                                    tag: 'tr',
                                    children: [{
                                       tag: 'td', cls: 'separator standard',
                                       colspan: 2,
                                       html: '&nbsp;'
                                    }]
                                 }, {
                                    tag: 'tr',
                                    children: [{
                                       id: 'numofmonths',
                                       tag: 'td', cls: 'standard',
                                       html: '&nbsp;'
                                    }, {
                                       id: 'payment',
                                       tag: 'td', cls: 'standard',
                                       html: '&nbsp;'
                                    }]
                                 }, {
                                    tag: 'tr',
                                    children: [{
                                       id: 'remain',
                                       tag: 'td', cls: 'standard',
                                       html: '&nbsp;'
                                    }, {
                                       id: 'remainpayment',
                                       tag: 'td', cls: 'standard',
                                       html: '&nbsp;'
                                    }]
                                 }]
                              }]
                           }, true); //Domhelp append
                           //                            IE doesn't seem to like this so I added it above
                           //                           Ext.DomHelper.append('table-head', {
                           //                              tag: 'tr',
                           //                              children: [{
                           //                                 tag: 'td', cls: 'heading standard colhead',
                           //                                 colspan: 2,
                           //                                 html: '<div >Level</div>Repayment'
                           //                              }]
                           //                           }, true);

                           //Ext.fly('levelTable').boxWrap('x-box');
                           Ext.fly('repayDiv').fadeIn({
                              endOpacity: .95, //can be any value between 0 and 1 (e.g. .5)
                              easing: 'easeIn',
                              duration: 1
                           })

                        } // end of create table

                        var obj = Ext.decode(action.response.responseText);
//                        if (obj.pfhpmt >= 0) {
                        if (obj.pfhpmt != -1) {
                           //hardship

                           pfhObj.pfhpmt = obj.pfhpmt;
                           pfhObj.pfhterm = obj.term;
                           pfhObj.pfhrate = obj.rate;
                           pfhObj.pfhpayment = obj.pfhpmt;
                           pfhObj.pfhloanamt = obj.loanamt;
                           pfhObj.pfhnumofmonths = 12;
                           pfhObj.pfhremain = obj.term - 12;

                           var remain_bal = calculate_balance_remain(obj.pfhpmt, obj.loanamt, obj.rate / 1200, pfhObj.pfhnumofmonths)
                           var remain_pmt = calculate_remain_payments(remain_bal, 0.0, obj.rate / 1200, pfhObj.pfhremain)
                           var pfhtotpmt = (pfhObj.pfhnumofmonths * obj.pfhpmt + pfhObj.pfhremain * remain_pmt);

                           pfhObj.pfhtotint = round_decimals(pfhtotpmt - obj.loanamt, 2);
                           pfhObj.pfhtotpay = pfhtotpmt;
                           pfhObj.pfhremainpayment = remain_pmt;

                           Ext.fly('qualify').fadeOut({
                              easing: 'easeOut',
                              useDisplay:true,
                              duration: .5
                           });
                        }
                        else {
                           Ext.fly('qualify').fadeIn({
                              endOpacity: .95, //can be any value between 0 and 1 (e.g. .5)
                              easing: 'easeIn',
                              duration: 1
                           });
                        }

                        fill_payment_table(pfhObj);
                        fill_payment_table(obj);
                     },
                     failure: function(form, action) {
                        Ext.MessageBox.show({
                           title: 'Error',
                           //                         msg: action.response.responseText,
                           msg: 'server-side failure with status code ' + action.response.status,
                           buttons: Ext.MessageBox.OK,
                           icon: Ext.MessageBox.ERROR
                        });
                     }
                  });
               }
            }, //end of calculate handler
            scope: this
         }], //end of button config
         trackResetOnLoad: true,
         items: [{
            html: 'Use this calculator to <i>estimate</i> your monthly student loan payment using the Income-Based Repayment (IBR) option.  View the <a href="http://www.ibrinfo.org/" target="_blank">IBR Video</a> for more information. Contact your lender to apply, and for the actual payment amount.<br><br>NOTE: This estimate does not include spousal income or spousal student loan debt.  ',
            bodyStyle: 'background-color: transparent; padding-bottom:10px; ',
            border: false         
         }, {
            layout: 'column',
            border: false,
            bodyStyle: 'background-color: transparent; ',
            items: [{
               columnWidth: .5,
               border: false,
               bodyStyle: 'background-color: transparent; ',
               items: [
                  new Ext.form.FieldSet({
                     title: 'Personal Information',
                     style: 'border: none; margin:0; padding:0;',
                     autoHeight: true,
                     defaultType: 'numberfield',
                     defaults: {
                        width: 120
                     },
                     items: [{
                        allowBlank: false,
                        fieldLabel: 'State of Residence',
                        xtype: 'combo',
                        hiddenName: 'residence',
                        store: new Ext.data.SimpleStore({
                           fields: ['abbr', 'state'],
                           data: stateData
                        }),
                        valueField: 'abbr',
                        displayField: 'state',
                        typeAhead: true,
                        mode: 'local',
                        triggerAction: 'all',
                        emptyText: 'Select a state...',
                        selectOnFocus: true,
                        forceSelection: true
                     }, {
                        fieldLabel: 'Family Size&nbsp;<span id="householdtip" class="x-form-ellips-trigger">&nbsp;&nbsp;&nbsp;&nbsp;</span>',
                        allowBlank: false,
                        allowDecimals: false,
                        name: 'household',
                        id: 'household'
                     }, {
                     //                     fieldLabel: 'Adjusted Gross Income (<span id="tip1" style="font-size:7pt;">AGI</span>)',
                     //                     fieldLabel: 'Adjusted Gross Income <img id="tip1" src="img/icon-question-small.gif" />',
                        fieldLabel: 'Adjusted Gross Income&nbsp;<span id="agitip" class="x-form-ellips-trigger">&nbsp;&nbsp;&nbsp;&nbsp;</span>',
                        allowDecimals: false,
                        allowBlank: false,
                        name: 'agi',
                        id: 'agi'
                     }]
                  })
               ]
            }, {
               columnWidth: .5,
               border: false,
               bodyStyle: 'background-color: transparent; ',
               items: [
                  new Ext.form.FieldSet({
                     title: 'Loan Information',
                     //                  style: 'border: none; margin:8px 0 0 0; padding:0; ',
                     style: 'border: none; margin:0; padding:0;',
                     autoHeight: true,
                     defaultType: 'numberfield',
                     defaults: {
                        width: 120
                     },
                     items: [{
                        fieldLabel: 'Amount owed on eligible student loans&nbsp;<span id="amounttip" class="x-form-ellips-trigger">&nbsp;&nbsp;&nbsp;&nbsp;</span>',
                        allowBlank: false,
                        name: 'amount',
                        id: 'amount'
                     }, {
                        fieldLabel: 'Average Student Loan Interest Rate&nbsp;<span id="ratetip"class="x-form-ellips-trigger">&nbsp;&nbsp;&nbsp;&nbsp;</span>',
                        allowBlank: false,
                        width: 50,
                        value: 0.0,
                        name: 'rate',
                        id: 'rate'
                     }]
                  })
               ]
            }]
         }]
      }); // end of form panel config
      
      var test = this.imageHTML;
      var p = new Ext.Panel({
         frame: false,
         border: false,
         items: [{
            xtype:'panel',
            id:'imagePreview', //give it a component id for later updating
            style:'margin:0px; margin-bottom: -2px ',
            frame: false,
            border: false,
            html: this.imageHTML
         }, 
            this.form
         ]
      });
      p.render('uiDiv');
//      Ext.fly('uiDiv').fadeIn({
//         endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
//         easing: 'easeOut',
//         duration: .5
//      })

//      this.form.render('uiDiv');

      this.form.getForm().load({
         url: 'IBRload.asp',
         waitMsg: 'Loading ...',
         params: {
            newStatus: 'delivered'
         },
         failure: function(form, action) {
            Ext.MessageBox.show({
               title: 'Error',
               msg: action.response.responseText,
               buttons: Ext.MessageBox.OK,
               icon: Ext.MessageBox.ERROR
            });
         },
         success: function(form, action) {
            //               console.log(action.result.data);
            var data = action.result.data
            new Ext.ToolTip({
               target: 'agitip',
               html: 'Adjusted Gross Income (AGI) is income from taxable sources (gross income) less tax deductions that are allowable even if you do not itemize deductions on your tax return.<br><br> \
               If you filed "single" on your tax return last year but plan to file a joint return this year, add your spouse’s AGI to yours when estimating your current AGI.<br><br> \
               Your AGI can be found on <div class="x-tip-body line">line ' + data.agi_1040 + ' of taxform 1040,</div><div class="x-tip-body line">line ' + data.agi_1040A + ' of taxform 1040A and </div><div class="x-tip-body line">line ' + data.agi_1040EZ + ' of taxform 1040EZ.</div>',
               dismissDelay: 20000 // auto hide after 15 seconds
               //                  title: 'My Tip Title',
               //                  autoHide: false,
               //                  closable: true,
               //                  draggable: true
            });

//            var tf = Ext.getCmp('agi');
//            Ext.QuickTips.register({
//               target: tf,
//               //               title: 'AGI',
//               text: 'Adjusted Gross Income (AGI) is income from taxable sources (gross income) less tax deductions that are allowable even if you do not itemize deductions on your tax return.<br><br> \
//               If you filed "single" on your tax return last year but plan to file a joint return this year, add your spouse’s AGI to yours when estimating your current AGI.<br><br> \
//               Your AGI can be found on <div class="x-tip-body line">line ' + data.agi_1040 + ' of taxform 1040,</div><div class="x-tip-body line">line ' + data.agi_1040A + ' of taxform 1040A and </div><div class="x-tip-body line">line ' + data.agi_1040EZ + ' of taxform 1040EZ.</div>',
//               dismissDelay: 20000 // auto hide after 15 seconds
//            });

            new Ext.ToolTip({
               target: 'householdtip',
               html: 'Includes you, your spouse, your children, and other dependents if they live with you and get more than half of their support from you.',
               dismissDelay: 15000 
            });
            new Ext.ToolTip({
               target: 'amounttip',
               html: 'Include any Stafford, Grad PLUS or Consolidation loan under the Direct Loan or FFEL program.&nbsp;&nbsp;Do not include any parent PLUS loans.',
               dismissDelay: 15000
            });
            new Ext.ToolTip({
               target: 'ratetip',
               html: '6.8% is the most common student loan interest rate.&nbsp;&nbsp;If you know the average interest rate for your eligible student loans, use it instead.',
               dismissDelay: 15000
            });
         }
      });

   } //end of init

};            //end of LoginSection