Ext.override(Ext.form.Field, {
  afterRender: Ext.form.Field.prototype.afterRender.createSequence(function(){
    if(this.qtip){
      var label = this.findLabel()
      var helpImage = label.createChild({
          tag:"img",
          src:"/znq_local/img/information.png",
          style:"margin:0;padding:0;cursor:help;position:absolute;right:2px;top:3px",
          width:16,
          height:16
      });
      if(typeof this.qtip == "object"){
        Ext.QuickTips.register(Ext.apply({
          target: helpImage
          }, this.qtip)
        );
      } else {
        helpImage.dom.qtip = this.qtip;
      }
    }
  })
  ,findLabel: function() {
    var wrapDiv = null;
    var label = null;
    wrapDiv = this.getEl().up("div.x-form-item");
    if(wrapDiv)
      label = wrapDiv.child("label");
    if(label)
      return label;
  }
});

function show_ploans_page() {
  Ext.get("page").update('<iframe width="620" height="730" frameborder="0" src="http://www.platinumcarloans.com.au/car-finance/options/personal-loan.html?content_only=yes&size=small"></iframe>');
}

function show_znq_form() {
  
  frmQuickEnquiry = new Ext.FormPanel({
    frame: false
    ,border: false
    ,id: "znq"
    ,defaultType: "textfield"
    ,monitorValid: true
    ,width: 335
    ,labelWidth: 130
    ,defaults: {
      width: 180
    }
    ,listeners: {
      "afterlayout": check_gst
    }
    ,items: [{
        xtype: "hidden"
        ,name: "referrer"
        ,value: znq_referrer
      },{
        xtype: "hidden"
        ,name: "sourceURL"
        ,value: (window.decodeURI)?window.decodeURI(document.URL):document.URL
      },{
        name: "first_name"
        ,fieldLabel: "First Name"
        ,allowBlank: false
      },{
        name: "last_name"
        ,fieldLabel: "Last Name"
        ,allowBlank: false
      },{
        name: "email"
        ,fieldLabel: "Email"
        ,vtype:'email'
        ,allowBlank: false
      },{
        xtype: "combo"
        ,name: "state"
        ,fieldLabel: "State"
        ,mode: "local"
        ,triggerAction: "all"
        ,lazyInit: true
        ,allowBlank: false
        ,forceSelection: true
        ,typeAhead: true
        ,inputType: "text"
        ,store: ["ACT","NSW","NT","QLD","SA","TAS","VIC","WA"]
      },{
         name: "mobile"
        ,fieldLabel: "Mobile"
        ,allowBlank: false
      },{
         name: "daytime_phone"
        ,fieldLabel: "Daytime Phone"
        ,allowBlank: false
      },{
        xtype: "combo"
        ,name: "age"
        ,hiddenName: "age"
        ,fieldLabel: "Vehicle Age"
        ,valueField: "age"
        ,displayField: "year"
        ,mode: "local"
        ,triggerAction: "all"
        ,lazyInit: true
        ,allowBlank: false
        ,forceSelection: true
        ,typeAhead: true
        ,inputType: "text"
        ,store: new Ext.data.SimpleStore({
          fields: ["age", "year"]
          ,data: [
            ["0", "new"]
            ,["1", "1 year"]
            ,["2", "2 years"]
            ,["3", "3 years"]
            ,["4", "4 years"]
            ,["5", "5 years"]
            ,["6", "6 years"]
            ,["7", "7 years"]
            ,["8", "8 years"]
            ,["9", "9+ years"]
          ]
        })
      },{
        xtype: "radiogroup"
        ,fieldLabel: "Buying Vehicle From"
        ,allowBlank: false
        ,width: 180
        ,items: [{
            boxLabel: "Dealer"
            ,name: "private_sale"
            ,inputValue: "false"
          },{
            boxLabel: "Other"
            ,name: "private_sale"
            ,id: "znq_private_sale-true"
            ,inputValue: "true"
          }
        ]
        ,listeners: {
          "change": check_gst
        }
      },{
        xtype: "combo"
        ,name: "product_code"
        ,id: "znq_product_code"
        ,hiddenName: "product_code"
        ,fieldLabel: "Finance Type"
        ,valueField: "code"
        ,displayField: "name"
        ,mode: "local"
        ,triggerAction: "all"
        ,lazyInit: true
        ,allowBlank: false
        ,forceSelection: true
        ,typeAhead: true
        ,inputType: "text"
        ,store: new Ext.data.SimpleStore({
          fields: ["code", "name"]
          ,data: [
            ["CON0", "Consumer Loan"]  
            ,["CHP0", "Hire Purchase"]
            ,["CHM0", "Chattel Mortgage"]
            ,["FIN1", "Finance Lease"]
            ,["NVL1", "Novated Lease"]
            ,["a", "Personal Loan"]  
          ]
        })
        ,listeners: {
          select: function(a,b,c) {
            if(c == 5) {
              show_ploans_page();
            } else {
              check_gst();
            }
          }
        }
      },{
        xtype: "combo"
        ,name: "term"
        ,hiddenName: "term"
        ,fieldLabel: "Term"
        ,valueField: "months"
        ,displayField: "term"
        ,mode: "local"
        ,triggerAction: "all"
        ,lazyInit: true
        ,allowBlank: false
        ,forceSelection: true
        ,typeAhead: true
        ,inputType: "text"
        ,store: new Ext.data.SimpleStore({
          fields: ["months", "term"]
          ,data: [
            ["36", "36 Months"]
            ,["48", "48 Months"]
            ,["60", "60 Months"]
          ]
        })
      },{
         name: "asset_cost"
        ,id: "znq_asset_cost"
        ,fieldLabel: "Finance Amount $"
        ,allowBlank: false
        ,enableKeyEvents: true
        ,qtip: "The finance amount = purchase price of the vehicle less any trade in or cash deposit"
      },{
         name: "balloon_dollar"
        ,fieldLabel: "Balloon Amount $"
        ,allowBlank: true
        ,qtip: "A balloon or residual is a lump sum payment made at the end of the finance term. A balloon is used to reduce the monthly repayment and can make the repayment more affordable."
      },{
        xtype: "fieldset"
        ,id: "znq_fs_gst_dollar"
        ,autoHeight: true
        ,style: {
          padding: "0"
          ,marginBottom: "0"
        }
        ,border: false
        ,width: 335
        ,defaults: {
          width: 180
        }
        ,items: [
          {
            xtype: "textfield"
            ,name: "gst_dollar"
            ,id: "znq_gst_dollar"
            ,fieldLabel: "GST $"
          }        
        ]
      },{
        xtype: "label"
        ,cls: "small x-form-item"
        ,html: "By clicking the <em>Get Instant Quote</em> button you agree a Platinum Direct Finance consultant can call you to discuss the finance quote and your car finance requirements."
        ,border:false
        ,height: 40
        ,width: 315
      },{
        xtype: "checkboxgroup"
        ,hideLabel: true
        ,cls: "newsletter_opt_in_field"
        ,width: 315
        ,height: 35
        ,items: [{
            boxLabel: "Yes I would like to subscribe to the Platinum Direct Finance Australia monthly Newsletter."
            ,name: "newsletter_opt_in"
            ,inputValue: "true"
            ,checked: false
          }
        ]
      },{
      xtype: "button"
      ,text: "Get Instant Quote"
      ,startText: "Get Instant Quote"
      ,id: "frmQuickEnquiry_btn"
      ,scale: "large"
      ,type: "submit"
      ,style: "margin: 0 auto 10px;"
      ,width: 170
      ,handler: function() {
        var theForm = Ext.getCmp("znq").getForm();
        if(theForm.isValid()) {
          var btn = Ext.getCmp("frmQuickEnquiry_btn");
          btn.disable();
          btn.setText("Calculating, please wait...");
          Ext.get("znq_answer_block").hide();
          theForm.submit({
            url: "/znq/quote"
            ,method: "POST"
            ,success: function(form, action) {
              showResult(form, action, btn);
            }
            ,failure: function(form, action) {
              problemWithResult(form, action, btn);
            }
          });
        }
      }
    }
    ]
  });
  frmQuickEnquiry.render("znq_question");

}

function showResult(form, action, btn) {
  btn.enable();
  btn.setText(btn.startText);
  var tpl = new Ext.XTemplate(
    '<table class="result">',
    '<tr>',
      '<th style="width:144px">Lender</th>',
      '<th>Base Rate</th>',
      '<th>Customer Rate</th>',
      '<th>Setup Fee</th>',
      '<th>Monthly Payment</th>',
    '</tr>',
    '<tpl for="quotes">',
      '<tr>',
        '<td id="{[values["lender"].print.split(" ").join("").toLowerCase()]}">{[values["lender"].print]}</td>',
        '<tpl for="rates">',
          '<td class="rates align-center">{amount} %</td>',
        '</tpl>',
        '<tpl for="fees">',
          '<td class="align-center"><span class="money fee"><span class="symbol">$</span><span class="amount">{value_decimal}</span></span></td>',
        '</tpl>',
        '<tpl if="parent.ex_gst == false">',
          '<td class="align-center"><span class="money"><span class="symbol">$</span><span class="amount">{[this.payment(values["payments"], "Monthly Gross")]}</span></span></td>',
        '</tpl>',
        '<tpl if="parent.ex_gst">',
          '<td class="align-center"><span class="money-description"><span class="symbol">$</span><span class="amount"><span class="description">inc gst</span>{[this.payment(values["payments"], "Monthly Gross")]}</span></span></td>',
        '</tpl>',
      '</tr>',
    '</tpl>',
    '</table>', {
      payment: function(payments, description){
        var ret = null;
        Ext.each(payments, function(payment){
          if(payment.description == description) {
            ret = payment.amount
            return false
          }
        })
        return ret;
      }
    }
  );
  tpl.overwrite("znq_answer", action.result.quote);
  Ext.each(action.result.quote.quotes, set_tip);
  pdf_button(action.result.quote.id);
  Ext.get("expiry").update(action.result.quote.expiry);
  Ext.get("znq_extra").setDisplayed(true);
  Ext.get("znq_answer2").setDisplayed(true);
  Ext.get("znq_answer_block").show();
}

function problemWithResult(form, action, btn) {
  btn.enable();
  btn.setText(btn.startText);
  msg = "There was an error, we have been notified. Please try again shortly.";
  if(action.result) {
    if(action.result.msg) {
      msg = action.result.msg;
    }      
  }
  Ext.get("znq_answer").update(msg);
  Ext.get("znq_extra").setDisplayed(false);
  Ext.get("znq_answer2").setDisplayed(false);
  Ext.get("znq_answer_block").show();
  
}

function pdf_button(quote_id) {
  Ext.get("znq_answer_pdf").update("");
  new Ext.LinkButton({
    id: "znq_pdf_button"
    ,text: "Print PDF Quote"
    ,href: "/znq/quote/" + quote_id + ".pdf"
    ,target: "znq_pdf"
    ,scale: "large"
    ,width: 150
    ,renderTo: "znq_answer_pdf"
  });
}

function check_gst() {
  // if private is ticked and product is 1 - hide
  // if private is unticked and product is 1 - show
  // if private is unticked and product is 0 - hide
  var pc   = Ext.getCmp("znq_product_code");
  var ac   = Ext.getCmp("znq_asset_cost");
  var gd   = Ext.getCmp("znq_gst_dollar");
  var fsgd = Ext.getCmp("znq_fs_gst_dollar");
  var c1   = Ext.getCmp("znq_private_sale-true").checked;
  var c2   = pc.getValue().substr(3,4) == "1";
  var c3   = pc.getValue().substr(3,4) == "0";

  // upate product description box
  show_description(pc.getValue().substr(0,3));

  if (c3) {
    ac.removeListener("keyup", calc_gst);
    ac.removeListener("blur", calc_gst);
    fsgd.hide();
    gd.disable();
    gd.setValue("");
  } else if(c2 && !c1) {
    ac.on({
        'keyup': calc_gst
        ,'blur': calc_gst
    });
    gd.enable();
    calc_gst();
    fsgd.show();
  } else if(c2 && c1) {
    ac.removeListener("keyup", calc_gst);
    ac.removeListener("blur", calc_gst);
    fsgd.hide();
    gd.disable();
    gd.setValue("");
  } else {
    ac.removeListener("keyup", calc_gst);
    ac.removeListener("blur", calc_gst);
    fsgd.hide();
    gd.disable();
    gd.setValue("");    
  }
}

function calc_gst() {
  var d = Math.round(Ext.getCmp("znq_asset_cost").getValue() / 11 * 100)/100;
  var max = 5198.18
  Ext.getCmp("znq_gst_dollar").setValue(d < max ? d : max);
}

function show_description(code) {
  var tpl = new Ext.XTemplate(
    '<h3>{heading}</h3>',
    '<p>{text}</p>'
  );
  switch(code) {
    case "CHP":
      heading = "What is a Hire Purchase?";
      text = "Interest and depreciation may be claimed. This finance option may be ideal for companies and employees who use their vehicle for work purposes. This is also the most popular option for employees who receive a car allowance.";
      break;
    case "CHM":
      heading = "What is a Chattel Mortgage?";
      text = "Interest and depreciation may be claimed as a tax deduction. The GST on the purchase price of the vehicle may also be claimable.";
      break;
    case "CON":
      heading = "What is a Consumer Loan?";
      text = "This follows all UCCC rules and is a good option for all private use vehicles.";
      break;
    case "FIN":
      heading = "What is a Finance Lease?";
      text = "Also known as a Car Lease, Auto Lease, Vehicle Lease or Asset Lease. This is a rental agreement and could be a good option for most companies.";
      break;
    case "NVL":
      heading = "What is a Novated Lease?";
      text = "A Novated Lease is a 3 way agreement between the financier, the employee and employer. The employee may receive some very attractive taxation savings.";
      break;
    default:
      heading = "Platinum Direct Finance Australia";
      text = "Platinum Direct Finance can provide all 1300calculators.com.au users with the best car finance solution and lowest total cost finance packages. We will give you access to most of Australia's leading banks and finance providers and provide real service, real quick!";
  }
  tpl.overwrite("znq_product", {heading: heading, text: text});
  Ext.get("znq_product").setStyle({display: "block"});
}

function set_tip(quote){
  var value = "";
  var lender = quote.lender.print.split(" ").join("").toLowerCase();
  switch(lender) {
    case "esandafinance":
      value = "<strong>Esanda Fiannce</strong><p>One of Australia's largest asset-based finance companies who are a wholly owned subsidiary of ANZ bank. Esanda provides fast approvals, competitive interest rates based on your business or personal circumstances.</p><p>Finance options include Consumer Loans, Hire Purchase, Chattel Mortgage, Finance Lease and Novated Lease's.</p><strong>Fees and Charges</strong><ul><li>Esanda Consumer Loans have a loan administration charge of $5 per month (pro-rata for fortnightly and irregular payments).</li><li>There is a loan establishment fee of $250 for Consumer Loans and $385 for all commercial based loans which can either be paid upfront or included in the loan amount.</li><li>Depending on which state you reside in government fees which will apply such as Stamp Duty and REVS fees.</li><li>A Late Payment Fee of $35 applies to any payments that are not received within 7 days of the due date.</li><li>If you require additional statements an Additional Statement Fee of $20 will be charged.</li><li>If you terminate your contract earlier than the contractual term, a fee (Early Termination Fee) will be charged proportional to the expired term of the contract. However if there has been a decline in prevailing interest rates you may also incur an additional interest recovery charge (Early Payment Loss).</li><li>For all vehicles purchased from a non-franchise dealer a fee of $195 is charged upfront (payable to Platinum Direct Finance Australia). This fee covers a sighting inspection, a V-Check (checks vehicle identifiers and age of vehicle), Revs Check (check to see if there is money owing on the vehicle and if the vehicle was a repairable write-off) and a dealer license check. These measures are put in place to help you make an informative decision about your vehicle purchase. Note: This is not a mechanical inspection.</li></ul><strong>Want To Talk To A Finance Consultant Now?</strong><p>Platinum Direct Finance can tailor a finance package to suit most individual or business requirements.</p><p>So if you would like to speed up the finance process, call an experienced finance consultant now on 1300 554 553.</p>";
      break;
    case "commonwealthbank":
      value = "<strong>Commonwealth Bank of Australia</strong><p>The Commonwealth Bank is one of Australia's most recognised brands and is also a leading provider of integrated financial services which includes Car Finance.</p><p>Car Finance options include Consumer Loans, Hire Purchase, Chattel Mortgage, Finance Lease and Novated Lease's.</p><strong>Fees and Charges</strong><ul><li>There is a loan establishment fee of $385 for all car loans which can either be paid upfront or included in the loan amount.</li><li>Depending on which state you reside in government fees which will apply such as Stamp Duty and REVS fees.</li><li>An Asic Fee is payable for all Chattel Mortgage contracts.</li><li>If you terminate your contract earlier than the contractual term, a fee (Early Termination Fee) will be charged and some of the remaining interest payable may be charged and added to the payout figure.</li><li>For all vehicles purchased from a non-franchise dealer a fee of $195 is charged upfront (payable to Platinum Direct Finance Australia). This fee covers a sighting inspection, a V-Check (checks vehicle identifiers and age of vehicle), Revs Check (check to see if there is money owing on the vehicle and if the vehicle was a repairable write-off) and a dealer license check. These measures are put in place to help you make an informative decision about your vehicle purchase. Note: This is not a mechanical inspection.</li></ul><strong>Want To Talk To A Finance Consultant Now?</strong><p>Platinum Direct Finance can tailor a finance package to suit most individual or business requirements.</p><p>So if you would like to speed up the finance process, call an experienced finance consultant now on 1300 554 553.</p>";
      break;
    case "macquarie":
      value = "<strong>Macquarie Leasing</strong><p>Macquarie Leasing sources lending opportunities from third party introducers, brokers, accountants, suppliers and motor dealerships.</p><p>Macquarie offers flexible and efficient leasing operations through the following car finance options including Personal Lease, Hire Purchase, Chattel Mortgage, Finance Lease and Novated Lease's.</p><strong>Fees and Charges</strong><ul><li>There is a loan establishment fee of $385 for all car loans which can either be paid upfront or included in the loan amount.</li><li>Personal Lease Loans have a loan administration charge of $4.95 per month</li><li>Depending on which state you reside in government fees which will apply such as Stamp Duty and REVS fees.</li><li>An Asic Fee is payable for all Chattel Mortgage contracts.</li><li>If you terminate your contract earlier than the contractual term, there is no Early Termination Fee. However the discount interest rule is applied to all payout figures where the contract is terminated before the contractual term.</li><li>For all vehicles purchased from a non-franchise dealer a fee of $195 is charged upfront (payable to Platinum Direct Finance Australia). This fee covers a sighting inspection, a V-Check (checks vehicle identifiers and age of vehicle), Revs Check (check to see if there is money owing on the vehicle and if the vehicle was a repairable write-off) and a dealer license check. These measures are put in place to help you make an informative decision about your vehicle purchase. Note: This is not a mechanical inspection.</li></ul><strong>Want To Talk To A Finance Consultant Now?</strong><p>Platinum Direct Finance can tailor a finance package to suit most individual or business requirements.</p><p>So if you would like to speed up the finance process, call an experienced finance consultant now on 1300 554 553.</p>";
      break;
    case "capitalfinance":
      value = "<strong>Capital Finance</strong><p>Capital Finance was founded in 1995. Since then they've become one of Australia's leading finance companies. Capital Finance are part of the HBOS Australia Group and parent Lloyds Banking Group is one of the world's largest financial services groups, with assets in excess of A$1 trillion.</p><p>Car Finance options include Hire Purchase, Chattel Mortgage, Finance Lease and Novated Lease's.</p><strong>Fees and Charges</strong><ul><li>There is a loan establishment fee of $300 for all car loans which can either be paid upfront or included in the loan amount.</li><li>Depending on which state you reside in government fees which will apply such as Stamp Duty and REVS fees.</li><li>An Asic Fee is payable for all Chattel Mortgage contracts.</li><li>If you terminate your contract earlier than the contractual term, a fee (Early Termination Fee) will be charged and some of the remaining interest payable may be charged and added to the payout figure.</li><li>For all vehicles purchased from a non-franchise dealer a fee of $195 is charged upfront (payable to Platinum Direct Finance Australia). This fee covers a sighting inspection, a V-Check (checks vehicle identifiers and age of vehicle), Revs Check (check to see if there is money owing on the vehicle and if the vehicle was a repairable write-off) and a dealer license check. These measures are put in place to help you make an informative decision about your vehicle purchase. Note: This is not a mechanical inspection.</li></ul><strong>Want To Talk To A Finance Consultant Now?</strong><p>Platinum Direct Finance can tailor a finance package to suit most individual or business requirements.</p><p>So if you would like to speed up the finance process, call an experienced finance consultant now on 1300 554 553.</p>";
      break;
    case "bankofqueensland":
      value = "<strong>Bank Of Queensland</strong><p>Bank of Queensland is Australia's fastest-growing retail bank with a network of more than 280 branches, and is one of the country's top 100 listed companies.</p><p>Car Finance options include Hire Purchase, Chattel Mortgage, Finance Lease and Novated Lease's.</p><strong>Fees and Charges</strong><ul><li>There is a loan establishment fee of $350 for all car loans which can either be paid upfront or included in the loan amount.</li><li>Depending on which state you reside in government fees which will apply such as Stamp Duty and REVS fees.</li><li>An Asic Fee is payable for all Chattel Mortgage contracts.</li><li>Through an exclusive arrangement with BOQ, all clients of the Platinum Direct Finance Group will receive no payout penalties as part of the finance contract.</li><li>For all vehicles purchased from a non-franchise dealer a fee of $195 is charged upfront (payable to Platinum Direct Finance Australia). This fee covers a sighting inspection, a V-Check (checks vehicle identifiers and age of vehicle), Revs Check (check to see if there is money owing on the vehicle and if the vehicle was a repairable write-off) and a dealer license check. These measures are put in place to help you make an informative decision about your vehicle purchase. Note: This is not a mechanical inspection.</li></ul><strong>Want To Talk To A Finance Consultant Now?</strong><p>Platinum Direct Finance can tailor a finance package to suit most individual or business requirements.</p><p>So if you would like to speed up the finance process, call an experienced finance consultant now on 1300 554 553.</p>";
      break;
    case "westpac":
      value = "<strong>Westpac</strong><p>Westpac is Australia's first bank and first company. They have 192 years experience helping customers to achieve their financial goals through good times and bad.</p><p>Car Finance options include Hire Purchase, Chattel Mortgage, Finance Lease and Novated Lease's.</p><strong>Fees and Charges</strong><ul><li>There is a loan establishment fee of $350 for all car loans which can either be paid upfront or included in the loan amount.</li><li>Depending on which state you reside in government fees which will apply such as Stamp Duty and REVS fees.</li><li>An Asic Fee is payable for all Chattel Mortgage contracts.</li><li>If you terminate your contract earlier than the contractual term, a fee (Early Termination Fee) will be charged and some of the remaining interest payable may be charged and added to the payout figure.</li><li>For all vehicles purchased from a non-franchise dealer a fee of $195 is charged upfront (payable to Platinum Direct Finance Australia). This fee covers a sighting inspection, a V-Check (checks vehicle identifiers and age of vehicle), Revs Check (check to see if there is money owing on the vehicle and if the vehicle was a repairable write-off) and a dealer license check. These measures are put in place to help you make an informative decision about your vehicle purchase. Note: This is not a mechanical inspection.</li></ul><strong>Want To Talk To A Finance Consultant Now?</strong><p>Platinum Direct Finance can tailor a finance package to suit most individual or business requirements.</p><p>So if you would like to speed up the finance process, call an experienced finance consultant now on 1300 554 553.</p>";
      break;
    case "nopayoutpenalty":
      value = "<strong>No Payout Penalty</strong><p>If you would like to speed up the finance process, call an experienced finance consultant now on 1300 554 553.</p>";
      break;
  }
  if(value != "") {
    var lenderEl = Ext.get(lender);
    lenderEl.update("");
    var info = lenderEl.createChild({
        tag:"img"
        ,src:"/znq_local/img/information.png"
        ,style:"margin:0;padding:0 0 0 2px;cursor:help;float:right;"
        ,width:16
        ,height:16
    });
    Ext.QuickTips.register({
      target: info
      ,text: value
      ,width: 500
    });
    lenderEl.createChild({
      tag:"span"
      ,html: quote.lender.print
    })
  }
}
Ext.onReady(function(){
  Ext.BLANK_IMAGE_URL = "/images/s.gif";
  Ext.QuickTips.init();
  Ext.form.Field.prototype.msgTarget = "side";
  
  Ext.apply(Ext.QuickTips.getQuickTip(),{dismissDelay: 0});
  if(Ext.get("znq_question")){show_znq_form();}
});
