/**
 * Installment Plan Info Module
 * 
 * @author  Kyo (AKA Yasuhiro Sota)
 * @version 1.1.3
 * @license Commercial License
 * @package admin
 * @subpackage  admin.view.javascript.installment_plan_info
 */
;(function($) {

  $.ModuleInstallmentPlanInfo = function () {};

  $.ModuleInstallmentPlanInfo.prototype = {
    translations: {
      'text_content': '',
      'text_confirm_delete_content': '',
      'text_content_top': '',
      'text_content_bottom': '',
      'text_column_left': '',
      'text_column_right': '',
      'text_custom_position': '',
      'text_enabled': '',
      'text_disabled': '',
      'text_check_all': '',
      'text_uncheck_all': '',
      'text_plan_calc_meth_equal': '',
      'text_plan_calc_meth_variable': '',
      'text_all': '',
      'entry_tab_name': '',
      'entry_key': '',
      'entry_title': '',
      'entry_title_link': '',
      'entry_general_promo_message': '',
      'entry_installment_plans': '',
      'entry_no_of_instal': '',
      'entry_plan_type_and_formula_type': '',
      'entry_installment': '',
      'entry_principal': '',
      'entry_interest': '',
      'entry_discount': '',
      'entry_plan_comment': '',
      'entry_plan_promo_msg': '',
      'entry_payment_methods': '',
      'entry_min_instal_amt': '',
      'entry_stores': '',
      'entry_access_levels': '',
      'entry_stylesheet': '',
      'entry_use_default_stylesheet': '',
      'button_remove': '',
      'button_add_installment_plan': ''
    }
  };
  
  function __(key) {
    var fc = new $.ModuleInstallmentPlanInfo();
    if (!fc.translations[key]) {
      return key;
    }
    return fc.translations[key];
  };
  
  $.extend({
    installmentPlanInfo: {
  /**
   * Default settings for the plugin
   */             
      settings: {
        translations: {},
        languages: [],
        payment_methods: [],
        formula_types: [],
        stores: [],
        customer_groups: [],
        layouts: [],
        image_base_url: 'view/image/installment_plan_info/',
        button_class: 'button',
        is_mijoshop: false,
        beforeInit: function() {},
        afterInit: function() {}
      },
  /**
   * init method
   *
   * @param el
   * @param settings
   * @return void
   */
      init: function(el, settings) {
        var _this = this;
        var $el = $(el);
        
        $('.ajax-loader').show();
        
        settings = settings || {};

        if (settings) {
          $.extend(_this.settings, settings);
        }
        
        _this.settings.beforeInit.call();
        
        var fc = new $.ModuleInstallmentPlanInfo();
        $.extend(fc.translations, settings.translations);
        

        $('.js-block-htabs a').tabs();
          
        _this.initGeneralSettings();
        _this.initModules();      

        // Automatically detect the height of the ".vtabs".
        $('.vtabs').height($(".vtabs-content-container").height());

        $(".vtabs-content-container").resize(function(e){
          var _height = $(this).height();
          if (_height > 0) {
            $('.vtabs').height(_height);
          }
        });
        
        $el.css({display: 'block'});
        $('.ajax-loader').hide();
        
        _this.settings.afterInit.call();
      },
  /**
   * initGeneralSettings method
   *
   * @param void
   * @return boolean
   */    
      initGeneralSettings: function() {
        var _this = this;

        _this.showHideScrollBar();
        
        var $tabs = $('.vtabs');

        $tabs.find('a').live('click', function() {
          $tabs.find('a').removeClass('selected');

          $tabs.find('a').each(function(i, element) {
            $($(element).attr('href')).hide();
          });

          $(this).addClass('selected');
          $($(this).attr('href')).show();
          
          $.cookie('installment_plan_info_selected_tab', $(this).index());

          return false;
        });

        // Get currently selected tab.
        if ($.cookie('installment_plan_info_selected_tab')) {
          $tabs.find('a').eq($.cookie('installment_plan_info_selected_tab')).trigger('click');
          
          // Tabs scrollbar
          $('.tabs-scrollbar').animate({ scrollTop: 40 * (Number($.cookie('installment_plan_info_selected_tab'))) }, 900);
        }
        
        // Tooltips
        _this._bindTabToolTip($tabs.find('a'));
        _this._bindInfoToolTip($('.vtabs-content').find('.info'));

       

      
        // Hide table header if no row on page init.
        $('.table-installment-plans').each(function(i, v) {
          if ($(v).find('tbody tr').length > 0) {
            $(v).show();
          }
        });
      
      
        $('#InstallmentPlanInfo').on('click', '.button-add-instal-plan',  function() {
          
          var content_id = $(this).parents('.vtabs-content').attr('data-content_id');
          var $tableWrap = $(this).closest('.installment-plans').find('.table-installment-plans-wrap');
          var $tables = $(this).closest('.installment-plans').find('.table-installment-plans');
          var sort_order = $tables.length;

          var _default = {
            'no_of_instal': '1',
            'formula_type': '1',
            'interest': ''
          };

          $lastTable = $tables.last();

          if ($lastTable.find('.input-no-of-instal').val()) {
            _default['no_of_instal'] = Number($lastTable.find('.input-no-of-instal').val()) + 1;
          }
          _default['interest'] = $lastTable.find('.input-interest').val();
          
          //  HTML for comments and promo messages
          var _html_comment = '', _html_promo_msg = '';
          
          $.each(_this.settings['languages'], function(i, language){
            _html_comment += '<div class="controls">';
            _html_comment += '  <img src="' + language['src'] + '" title="' + language['name'] + '" />';
            _html_comment += '  <input type="text" class="input-plan-comment" name="installment_plan_info_' + content_id + '[installment_plans][' + sort_order + '][comment][' + language['language_id'] + ']" value="" />';
            _html_comment += '</div>';

            _html_promo_msg += '<div class="controls">';
            _html_promo_msg += '  <img src="' + language['src'] + '" title="' + language['name'] + '" />';
            _html_promo_msg += '  <input type="text" class="input-plan-promo-msg" name="installment_plan_info_' + content_id + '[installment_plans][' + sort_order + '][promo_msg][' + language['language_id'] + ']" value="" />';
            _html_promo_msg += '</div>';
          });
          
          //  HTML for formulas
          var _html_formula_types = '';
          
          $.each(_this.settings['formula_types'], function(key, value){
            _html_formula_types += '<option value="' + key + '">' + value + '</option>';
          });    
          

          var _html = ' \
          <table class="table-installment-plans"> \
            <thead> \
              <tr> \
                <th>' + __('entry_no_of_instal') + '</th> \
                <th>' + __('entry_plan_type_and_formula_type') + '</th> \
                <th>' + __('entry_plan_comment') + '</th> \
                <th>' + __('entry_plan_promo_msg') + '</th> \
                <th></th> \
              </tr> \
            </thead> \
            <tbody> \
              <tr> \
                <td> \
                  <input type="text" class="input-no-of-instal" name="installment_plan_info_' + content_id + '[installment_plans][' + sort_order + '][no_of_instal]" value="' + _default['no_of_instal'] + '" maxlength="2" /> \
                </td> \
                <td class="plan-payments-wrap"> \
                  <div class="plan-type-wrap"> \
                    <select class="select-plan-type" name="installment_plan_info_' + content_id + '[installment_plans][' + sort_order + '][plan_type]"> \
                      <option value="1" >' + __('text_plan_calc_meth_equal') + '</option> \
                      <option value="2">' + __('text_plan_calc_meth_variable') + '</option> \
                    </select> \
                    <a href="#" class="button-add-indv-instl"> \
                      <img src="' + _this.settings['image_base_url'] + 'add.png" alt="" /> \
                    </a> \
                  </div> \
                  <div class="formula-type-wrap"> \
                    <select class="select-formula-type" name="installment_plan_info_' + content_id + '[installment_plans][' + sort_order + '][formula_type]"> \
                      <option value=""></option> \
                      ' + _html_formula_types + ' \
                    </select> \
                  </div> \
                  <table class="tbl-payments"> \
                    <thead> \
                      <tr> \
                        <th>' + __('entry_installment') + '</th> \
                        <th>' + __('entry_principal') + '</th> \
                        <th>' + __('entry_interest') + '</th> \
                        <th>' + __('entry_discount') + '</th> \
                        <th></th> \
                      </tr> \
                    </thead> \
                    <tbody> \
                    </tbody> \
                  </table> \
                </td> \
                <td>' + _html_comment + '</td> \
                <td>' + _html_promo_msg + '</td> \
                <td> \
                  <a href="#" class="button-delete-instal-plan"> \
                    <img src="' + _this.settings['image_base_url'] + 'delete.png" alt="" /> \
                  </a> \
                </td> \
              </tr> \
            </tbody> \
          </table>';
              
          $tableWrap.append(_html).show();
          
          $tableWrap.find('.table-installment-plans').last().find('.button-add-indv-instl').trigger('click');
          
          if ($tableWrap.find('.table-installment-plans').last().find('.select-plan-type').val() == 1) {
            $tableWrap.find('.table-installment-plans').last().find('.button-add-indv-instl').hide();
          }
          
          $tableWrap.find('.table-installment-plans').last().show();
          
          _this._bindInfoToolTip($tableWrap.find('.table-installment-plans').last().find('.info'));
          
          if ($tables.is(':hidden')) {
            $tables.show();
          }

          return false;
        });

        $('#InstallmentPlanInfo').on('click', '.button-delete-instal-plan',  function() {

          $(this).closest('.table-installment-plans').remove();

          return false;
        });
        

        $('#InstallmentPlanInfo').find('.table-installment-plans').each(function(i, v) {

          if ($(v).find('.select-plan-type').val() == 1) { // Equal payment plan
            $(v).find('.input-principal').prop('disabled', true);
            
            // Hide add button.
            $(v).find('.button-add-indv-instl').hide();
 
          } else if ($(v).find('.select-plan-type').val() == 2) { // Variable ayment plan
            $(v).find('.input-principal').prop('disabled', false);
          }
          
          // Set ".tbl-payments" display state on page load.
          if ($(v).find('.tbl-payments tbody tr').length <= 0) {
            $(v).find('.tbl-payments').hide();
          }
          
          // Set the state of add button on page load
          if (Number($(v).find('.input-no-of-instal').val()) <= $(v).find('.tbl-payments tbody tr').length) {
            $(v).find('.button-add-indv-instl').hide();            
          }
          
        });
      

        $('#InstallmentPlanInfo').on('change', '.select-plan-type',  function() {
          var _this = this;
          
          var _val = $(this).val();
          var $paymentsWrap = $(this).closest('.plan-payments-wrap');
          
          $paymentsWrap.find('.tbl-payments').find('tbody tr').remove();
          $paymentsWrap.find('.button-add-indv-instl').trigger('click');
          
          
          var $tblInstalPlans = $(this).closest('.table-installment-plans');
          var no_of_instal = Number($tblInstalPlans.find('.input-no-of-instal').val());
          
          if (_val == 2) {
            if (no_of_instal > $paymentsWrap.find('.tbl-payments').find('tbody tr').length) {
              $paymentsWrap.find('.button-add-indv-instl').show();            
            }              
          }
          
          return false;
        });
        
        // Add variable installment
        $('#InstallmentPlanInfo').on('click', '.button-add-indv-instl',  function() {
          
          var content_id = $(this).parents('.vtabs-content').attr('data-content_id');
          var $tblInstlPlans = $(this).closest('.table-installment-plans');
          var $tblPayments = $(this).closest('.plan-payments-wrap').find('.tbl-payments');          
          var sort_order = $tblInstlPlans.index();
          var payments_key = $tblPayments.find('tbody tr').length;
          var no_of_instal = Number($tblInstlPlans.find('.input-no-of-instal').val());
          var plan_type = $tblInstlPlans.find('.select-plan-type').val();
          
          if (no_of_instal <= 0) {
            return false;
          }
          
          var _html = '';
          
          _html += '<tr>';
          _html += ' <td>';
          _html += '  <select class="select-installment" name="installment_plan_info_' + content_id + '[installment_plans][' + sort_order + '][payments][' + payments_key + '][installment]">';
          
          if (plan_type == 1) {
            _html += '<option value="0">' + __('text_all') + '</option>';
            
          } else if (plan_type == 2) {

            $.each(_this.range(1, no_of_instal), function(i, v) {
              _html += '<option value="' + v + '">' + v + '</option>';
            });
          }
          
          _html += '  </select>';
          _html += ' </td>';
          _html += ' <td>';
          _html += '   <input type="text" class="input-principal" name="installment_plan_info_' + content_id + '[installment_plans][' + sort_order + '][payments][' + payments_key + '][principal]" ' + (plan_type == 1 || plan_type == 3 ? 'disabled="disabled"' : '') + ' value="" />';
          _html += ' </td>';
          _html += ' <td>';
          _html += '   <input type="text" class="input-interest" name="installment_plan_info_' + content_id + '[installment_plans][' + sort_order + '][payments][' + payments_key + '][interest]" value="" />';
          _html += ' </td>';
          _html += ' <td>';
          _html += '   <input type="text" class="input-discount" name="installment_plan_info_' + content_id + '[installment_plans][' + sort_order + '][payments][' + payments_key + '][discount]" value="" />';
          _html += ' </td>';
          _html += ' <td>';
          _html += '   <a href="#" class="button-delete-indv-instl' + (payments_key <= 0 ? ' disabled' : '') + '">';
          _html += '     <img src="' + _this.settings['image_base_url'] + 'delete' + (payments_key <= 0 ? '_disabled' : '') + '.png" alt="" />';
          _html += '   </a>';
          _html += ' </td>';
          _html += '</tr>';

          $tblPayments.find('tbody').append(_html);
          
          // Set selected option for installment.
          var $lastRow = $tblPayments.find('tbody tr').last();
          if ($lastRow.prev().find('.select-installment').val()) {
            $lastRow.find('.select-installment').val( Number($lastRow.prev().find('.select-installment').val()) + 1 );
          }

          if ($tblPayments.is(':hidden')) {
            $tblPayments.show();
          }
          
          // Hide add button if the number of table rows is equal to or greater than the maximum limit.
          if (no_of_instal <= $tblPayments.find('tbody tr').length) {
            $tblInstlPlans.find('.button-add-indv-instl').hide();
          }

          return false;
        });  
        
        // Delete variable installment
        $('#InstallmentPlanInfo').on('click', '.button-delete-indv-instl',  function() {

          if ($(this).hasClass('disabled')) {
            return false;
          }
          
          var $tblInstlPlans = $(this).closest('.table-installment-plans');
          var $tblPayments = $(this).closest('.tbl-payments');
          var no_of_instal = Number($tblInstlPlans.find('.input-no-of-instal').val());
          
          $(this).closest('tr').remove();

          if ($tblPayments.find('tbody tr').length <= 0) {
            $tblPayments.hide();
          }
          
          // Show add button if the number of table rows is less than the maximum limit.
          if (no_of_instal > $tblPayments.find('tbody tr').length) {
            $tblInstlPlans.find('.button-add-indv-instl').show();
          }
          
          return false;
        });
        
        
        $('#InstallmentPlanInfo').on('keyup paste', '.input-no-of-instal',  function() {

          var $tblInstlPlans = $(this).closest('.table-installment-plans');
          var $tblPayments = $tblInstlPlans.find('.tbl-payments');
          var no_of_instal = Number($(this).val());
          
          if (no_of_instal == 0) {
            no_of_instal = 1;
            $(this).val(no_of_instal);
          }
          
          if (no_of_instal <= $tblPayments.find('tbody tr').length) {
            // Hide add button if the number of table rows is equal to or greater than the maximum limit.
            $tblInstlPlans.find('.button-add-indv-instl').hide();
            
            // If the number of table rows is greater than no_of_instal, then remove it.
            $tblPayments.find('tbody tr').each(function(i, v) {
              if (no_of_instal < (i + 1)) {
                $(v).remove();
              }
            });            
            
          } else {
            if ($tblInstlPlans.find('.select-plan-type').val() != 1) {
              // Show add button if the number of table rows is less than the maximum limit and the plan type is set to "Variable".
              $tblInstlPlans.find('.button-add-indv-instl').show();
            }
          }        
        
          return true;
        });

       
        $('#InstallmentPlanInfo').on('keyup paste', '.input-no-of-instal', function(){          
          var s = new Array();
          $.each( $(this).val().split(''), function(i, v){
            if( v.match(/[0-9]/g) ) s.push(v);
          } );
          if(s.length > 0) {
            $(this).val( s.join('') );
          } else {
            $(this).val('');
          }
        });

        $('#InstallmentPlanInfo').on('keyup paste', '.input-min-instal-amt, .input-principal, .input-interest, .input-discount', function(){
          var s = new Array();
          $.each( $(this).val().split(''), function(i, v){
            if( v.match(/[0-9.]/g) ) s.push(v);
          } );
          if(s.length > 0) {
            $(this).val( s.join('') );
          } else {
            $(this).val('');
          }
        });


        // Create new content
        $('.button-create-new-content').click(function() {
          
          var content_id = $tabs.find('a').length + 1;
          
          var languages = _this.settings['languages'];
          
          // Title HTML
          var _html_entry_title = '';
          
          $.each(languages, function(i, language){
            _html_entry_title += '<div class="controls">';
            _html_entry_title += '  <img src="' + language['src'] + '" title="' + language['name'] + '" />';
            _html_entry_title += '  <input type="text" class="input-title" name="installment_plan_info_' + content_id + '[title][' + language['language_id'] + ']" data-language_id="' + language['language_id'] + '" value="" />';
            _html_entry_title += '</div>';
          });
          
          // Title HTML
          var _html_entry_general_promo_message = '';
          
          $.each(languages, function(i, language){
            _html_entry_general_promo_message += '<div class="controls">';
            _html_entry_general_promo_message += '  <img src="' + language['src'] + '" title="' + language['name'] + '" />';
            _html_entry_general_promo_message += '  <input type="text" class="input-general-promo-message" name="installment_plan_info_' + content_id + '[general_promo_message][' + language['language_id'] + ']" value="" />';
            _html_entry_general_promo_message += '</div>';
          });
          
          // Stores HTML
          var _html_entry_stores = '', stores = _this.settings['stores'];
          
          _html_entry_stores += '<div class="scrollbox-installment-plan-info-stores scrollbox">';
          var _class = 'odd';
          $.each(stores, function(i, store){
            _class = (_class == 'even') ? 'odd' : 'even';
            _html_entry_stores += '<div class="' + _class + '">';
            _html_entry_stores += '  <label>';
            if (store['store_id'] == 0) {
              _html_entry_stores += '    <input type="checkbox" name="installment_plan_info_' + content_id + '[stores][]" value="' + store['store_id'] + '"  checked="checked" />';
            } else {
              _html_entry_stores += '    <input type="checkbox" name="installment_plan_info_' + content_id + '[stores][]" value="' + store['store_id'] + '" />';
            }
            _html_entry_stores += '    ' + store['name'] + '';
            _html_entry_stores += '  </label>';
            _html_entry_stores += '</div>';
          });
          _html_entry_stores += '</div>';

          // Access levels HTML
          var _html_entry_access_levels = '', customer_groups = _this.settings['customer_groups'];
          
          _html_entry_access_levels += '<div class="scrollbox-installment-plan-info-access-levels scrollbox">';
          _class = 'odd'; // Reset _class variable
          $.each(customer_groups, function(i, customer_group){
            _class = (_class == 'even') ? 'odd' : 'even';
            _html_entry_access_levels += '<div class="' + _class + '">';
            _html_entry_access_levels += '  <label>';
            _html_entry_access_levels += '    <input type="checkbox" name="installment_plan_info_' + content_id + '[access_levels][]" value="' + customer_group['customer_group_id'] + '" checked="checked" />';
            _html_entry_access_levels += '    ' + customer_group['name'] + '';
            _html_entry_access_levels += '  </label>';
            _html_entry_access_levels += '</div>';
          });
          _html_entry_access_levels += '</div>';
          

          // Payment Methods HTML
          var _html_entry_payment_methods = '', payment_methods = _this.settings['payment_methods'];
          
          _html_entry_payment_methods += '<ul class="payment-methods">';
          var _class = 'odd';
          $.each(payment_methods, function(key, payment_method){
            _class = (_class == 'even') ? 'odd' : 'even';
            _html_entry_payment_methods += '<li class="' + _class + '">';
            if (payment_method['thumb']) {
              _html_entry_payment_methods += '<img src="' + payment_method['thumb'] + '" alt="' + payment_method['name'] + '" />';  
            }
            _html_entry_payment_methods += '  <input type="hidden" class="input-hidden-payment-methods-status" name="installment_plan_info_' + content_id + '[payment_methods][' + key + '][status]" value="0" />';
            _html_entry_payment_methods += '  <label>';
            _html_entry_payment_methods += '    <input type="checkbox" class="input-checkbox-payment-methods-status" name="installment_plan_info_' + content_id + '[payment_methods][' + key + '][status]" value="1" />';
            _html_entry_payment_methods += '  ' + payment_method['name'] + '';
            _html_entry_payment_methods += '  </label>';
            _html_entry_payment_methods += '  <input type="text" class="input-payment-methods-no-of-instal" name="installment_plan_info_' + content_id + '[payment_methods][' + key + '][no_of_instal]" value="" maxlength="2" />';
            _html_entry_payment_methods += '</li>';
          });
          _html_entry_payment_methods += '</ul>';

          
          var _html_entry_min_instal_amt = '', currencies = _this.settings['currencies'];
          $.each(currencies, function(key, currency){
            _html_entry_min_instal_amt += '<div class="controls">';
            _html_entry_min_instal_amt += '  <label>' + currency['code'] + '</label>';
            _html_entry_min_instal_amt += '  <input type="text" class="input-min-instal-amt" name="installment_plan_info_' + content_id + '[min_instal_amt][' + currency['code'] + ']" value="" />';
            _html_entry_min_instal_amt += '</div>';
          });
          
          // HTML
          var html = {
            link: '\
              <a href="" data-content_id="" style="display: none;"> \
                <strong></strong> \
                <img src="' + _this.settings['image_base_url'] + 'delete.png" alt="" /> \
              </a>',
            content: '\
              <div id="tab-installment-plan-info-' + content_id + '" class="vtabs-content" data-content_id="' + content_id + '" style="display: none;"> \
                <table class="form"> \
                  <tr> \
                    <td>' + __('entry_tab_name') + '</td> \
                    <td> \
                      <input type="text" class="input-tab-name" name="installment_plan_info_' + content_id + '[tab_name]" value="" /> \
                    </td> \
                  </tr> \
                  <tr> \
                    <td>' + __('entry_key') + '</td> \
                    <td> \
                      <input type="text" class="input-key" name="installment_plan_info_' + content_id + '[key]" value="" /> \
                    </td> \
                  </tr> \
                  <tr> \
                    <td>' + __('entry_title') + '</td> \
                    <td>' + _html_entry_title + '</td> \
                  </tr> \
                  <tr> \
                    <td>' + __('entry_title_link') + '</td> \
                    <td> \
                      <input type="text" class="input-title-link" name="installment_plan_info_' + content_id + '[title_link]" value="" /> \
                    </td> \
                  </tr> \
                  <tr> \
                    <td>' + __('entry_general_promo_message') + '</td> \
                    <td>' + _html_entry_general_promo_message + '</td> \
                  </tr> \
                  <tr> \
                    <td>' + __('entry_stores') + '</td> \
                    <td> \
                      ' + _html_entry_stores + ' \
                      <div class="check-uncheck-all-container"> \
                        <a href="#" class="check-all-stores">' + __('text_check_all') + '</a> \
                        <a href="#" class="uncheck-all-stores">' + __('text_uncheck_all') + '</a> \
                      </div> \
                    </td> \
                  </tr> \
                  <tr> \
                    <td>' + __('entry_access_levels') + '</td> \
                    <td> \
                      ' + _html_entry_access_levels + ' \
                      <div class="check-uncheck-all-container"> \
                        <a href="#" class="check-all-access-levels">' + __('text_check_all') + '</a> \
                        <a href="#" class="uncheck-all-access-levels">' + __('text_uncheck_all') + '</a> \
                      </div> \
                    </td> \
                  </tr> \
                  <tr> \
                    <td>' + __('entry_stylesheet') + '</td> \
                    <td> \
                      <input type="hidden" class="input-hidden-use-default-stylesheet" name="installment_plan_info_' + content_id + '[use_default_stylesheet]" value="0" /> \
                      <label> \
                        <input type="checkbox" class="input-checkbox-use-default-stylesheet" name="installment_plan_info_' + content_id + '[use_default_stylesheet]" value="1" checked="checked" /> \
                        ' + __('entry_use_default_stylesheet') + ' \
                      </label> \
                      <div class="textarea-stylesheet-container"> \
                        <textarea class="textarea-stylesheet" name="installment_plan_info_' + content_id + '[stylesheet]" cols="50" rows="3"></textarea> \
                      </div> \
                    </td> \
                  </tr> \
                  <tr> \
                    <td>' + __('entry_payment_methods') + '</td> \
                    <td>' + _html_entry_payment_methods + '</td> \
                  </tr> \
                  <tr> \
                    <td>' + __('entry_min_instal_amt') + '</td> \
                    <td>' + _html_entry_min_instal_amt + '</td> \
                  </tr> \
                </table> \
                <table class="form form-no-border"> \
                  <tr> \
                    <td> \
                      <div class="installment-plans"> \
                        <div class="title-installment-plans">' + __('entry_installment_plans') + '</div> \
                        <div class="table-installment-plans-wrap"></div> \
                        <div class="button-add-instal-plan ipi-button"> \
                          <img src="' + _this.settings['image_base_url'] + 'add.png" alt="" /> \
                          <a href="#">' + __('button_add_installment_plan') + '</a> \
                        </div> \
                      </div> \
                    </td> \
                  </tr> \
                </table> \
              </div>'
          };

          $tabs.find('.tab-container').append(html.link);

          $newTabLink = $tabs.find('a:last');

          $newTabLink.attr('href', '#tab-installment-plan-info-' + content_id).attr('data-content_id', content_id);
          $newTabLink.find('strong').text(__('text_content') + ' ' + content_id);
          $newTabLink.fadeIn(300);
          
          // Scrollbar for the vertical tabs.
          _this.showHideScrollBar();

          // Deselect all the tabs.
          $tabs.find('a')
          .removeClass('selected')
          .each(function(i, element) {
            $($(element).attr('href')).hide();
          });

          $newTabLink.addClass('selected');
          $.cookie('installment_plan_info_selected_tab', $newTabLink.index());

          // Show new tab content.
          $('.vtabs-content-container').append(html.content);
          $('.vtabs-content-container').children('.vtabs-content').last().show();


          var $newTabContent = $($newTabLink.attr('href'));
          if ($('.input-checkbox-incl-dab-prods').first().is(':checked')) {
            $newTabContent.find('.input-checkbox-incl-dab-prods').attr('checked', true);
          } else {
            $newTabContent.find('.input-checkbox-incl-dab-prods').attr('checked', false);
          }

          // Update total count on entry add.    
          $('#time-payment-price-calculation-count').val($tabs.find('a').length);

          $('.select-module-content-id')
          .append($("<option></option>")
          .attr("value", content_id)
          .text(__('text_content') + ' ' + content_id));   
          
          // Tooltips
          _this._bindTabToolTip($newTabLink);
          _this._bindInfoToolTip($('#tab-installment-plan-info-' + content_id).find('.info'));          
          
          return false;
        });


        if ($tabs.find('a').length <= 0) {
          $('.button-create-new-content').trigger('click');
        }
        

        // Delete a tab and its content.
        $tabs.find('a img').live('click', function() {
          var content_id = $(this).parent('a').attr('data-content_id');

          $selects = $('.select-module-content-id', '#module');

          if ($selects.children('option[value=\'' + content_id + '\']:selected').length > 0) {
            if (!confirm(__('text_confirm_delete_content'))) {
              return false;
            }
          }

          $(this).parent('a').fadeOut(300).queue(function(){
            var _this_content_id = $(this).attr('href');

            if ($(this).hasClass('selected')) {
              if ($(this).is(':first-child')) {
                $(this).next('a').addClass('selected');
                $($(this).next('a').attr('href')).show();
                $.cookie('installment_plan_info_selected_tab', $(this).next('a').index());
              } else {
                $(this).prev('a').addClass('selected');
                $($(this).prev('a').attr('href')).show();
                $.cookie('installment_plan_info_selected_tab', $(this).prev('a').index());
              }
            }

            $($(this).attr('href')).remove();
            $(this).remove();

            _this.showHideScrollBar();

            // Update total count on entry delete.
            $('#time-payment-price-calculation-count').val($tabs.find('a').length);

            // Renumber the tab links.
            $tabs.find('a').each(function(i, v) {
              var new_content_id = i + 1;
              var old_content_id = $(v).attr('data-content_id');

              $(v).attr('href', '#tab-installment-plan-info-' + new_content_id);
              $(v).attr('data-content_id', new_content_id);

              if ($.trim($(v).find('strong').text()) == __('text_content') + ' ' + old_content_id) {
                $(v).find('strong').text(__('text_content') + ' ' + new_content_id); 
              }
            });

            // Renumber the tab contents.
            $('.vtabs-content-container > div').each(function(i, v) {
              
              var new_content_id = i + 1;

              
              $(this).attr('id', 'tab-installment-plan-info-' + new_content_id);
              $(this).attr('data-content_id', new_content_id);
              
              
              // Replace all name values.
              $(this).find('[name^=installment_plan_info_]').each(function(j, k) {
                $(k).attr('name', $(k).attr('name').replace(/^installment_plan_info_[\d]+/, 'installment_plan_info_' + new_content_id));
              });

              // Replace all id values.
              $(this).find('[id^=time-payment-price-calculation-]').each(function(j, k) {
                $(k).attr('id', $(k).attr('id').replace(/^time-payment-price-calculation-[\d]+/, 'time-payment-price-calculation-' + new_content_id));
              });

              // Replace all href values.
              $(this).find('[href^=#time-payment-price-calculation-]').each(function(j, k) {
                $(k).attr('href', $(k).attr('href').replace(/^#time-payment-price-calculation-[\d]+/, '#time-payment-price-calculation-' + new_content_id));
              });              
              
            });

            // Renumber option values in all the "content_id" select boxes.
            $selects.children('option[value=\'' + content_id + '\']').remove();
            $selects.each(function(i, v) {
              $(v).find("option").each(function(j, k) {
                if (Number($(k).val()) > Number(content_id)) {
                  if ($.trim($(k).text()) == __('text_content') + ' ' + Number($(k).val())) {
                    $(k).text(__('text_content') + ' ' + j);
                  }
                  $(k).val(j);
                }
              });
            });
          });

          return false;
        });        
        
        
        // Tab name
        $('#InstallmentPlanInfo').on('change keyup paste', '.input-tab-name',  function() {
          var content_id = $(this).closest('.vtabs-content').attr('data-content_id');
          $tab = $('.vtabs	> .tab-container').find("a[data-content_id='" + content_id +"']");

          var _value = $(this).val();

          if (!_value) {
            _value = __('text_content') + ' ' + content_id;
          }

          $tab.children('strong').text(_value);

          $('#module').find('.select-module-content-id').each(function(i, v) {
            $(v).children('option').each(function(j, k) {
              if ($(k).val() == content_id) {
                $(k).text(_value)
              }
            });
          });

          return true;
        });
        

        $('#InstallmentPlanInfo').on('click', '.check-all-access-levels',  function() {
          $(this).parents().prev('.scrollbox-installment-plan-info-access-levels').find(':checkbox').attr('checked', true);
          return false;
        });
        
        $('#InstallmentPlanInfo').on('click', '.uncheck-all-access-levels',  function() {
          $(this).parents().prev('.scrollbox-installment-plan-info-access-levels').find(':checkbox').attr('checked', false);
          return false;
        });

        $('#InstallmentPlanInfo').on('click', '.check-all-stores',  function() {
          $(this).parents().prev('.scrollbox-installment-plan-info-stores').find(':checkbox').attr('checked', true);
          return false;
        });

        $('#InstallmentPlanInfo').on('click', '.uncheck-all-stores',  function() {
          $(this).parents().prev('.scrollbox-installment-plan-info-stores').find(':checkbox').attr('checked', false);
          return false;
        });
        
      },
  /**
   * initModules method
   *
   * @param void
   * @return boolean
   */    
      initModules: function() {
        var _this = this;
        
        
        $('#button-add-module').click(function () {
          
          var module_row = $('#module-row').val();
          
          var installment_plan_info_count = $('#time-payment-price-calculation-count').val();
          
          var layouts = _this.settings['layouts'];
          
          html  = '<tbody id="module-row' + module_row + '">';
          html += '  <tr>';
          html += '    <td class="left">';
          html += '      <select class="select-module-content-id" name="installment_plan_info_module[' + module_row + '][content_id]">';
          html += '        <option value=""></option>';
          
          for (i = 1; i <= installment_plan_info_count; i++) {
            html += '        <option value="' + i + '">' + __('text_content') + ' ' + i + '</option>';
          }
          
          html += '      </select>';
          html += '    </td>';
          html += '    <td class="left"><input type="text" class="input-module-image-width" name="installment_plan_info_module[' + module_row + '][image_width]" value="48" size="3" /> <input type="text" class="input-module-image-height" name="installment_plan_info_module[' + module_row + '][image_height]" value="30" size="3" /></td>';	
          html += '    <td class="left"><select class="select-module-layout-id" name="installment_plan_info_module[' + module_row + '][layout_id]">';
          
          $.each(layouts, function(i, layout){
            html += '        <option value="' + layout['layout_id'] + '">' + layout['name'] + '</option>';
          });          
 
          html += '    </select></td>';
          html += '    <td class="left"><select class="select-module-position" name="installment_plan_info_module[' + module_row + '][position]">';
          html += '      <option value="content_top">' + __('text_content_top') + '</option>';
          html += '      <option value="content_bottom">' + __('text_content_bottom') + '</option>';
          html += '      <option value="column_left">' + __('text_column_left') + '</option>';
          html += '      <option value="column_right">' + __('text_column_right') + '</option>';
          html += '      <option value="installment_plan_info">' + __('text_custom_position') + '</option>';
          html += '    </select></td>';
          html += '    <td class="left"><select class="select-module-status" name="installment_plan_info_module[' + module_row + '][status]">';
          html += '      <option value="1" selected="selected">' + __('text_enabled') + '</option>';
          html += '      <option value="0">' + __('text_disabled') + '</option>';
          html += '    </select></td>';
          html += '    <td class="right"><input type="text" class="input-module-sort-order" name="installment_plan_info_module[' + module_row + '][sort_order]" value="" size="3" /></td>';
          html += '    <td class="left"><a href="#" class="' + _this.settings['button_class'] + '">' + __('button_remove') + '</a></td>';
          html += '  </tr>';
          html += '</tbody>';

          $('#module tfoot').before(html);


          var $select = $('select[name=\'installment_plan_info_module[' + module_row + '][content_id]\']');

          $select.children('option').each(function() {
            if ( $(this).val() != '' ) {
              $(this).remove();
            }
          });
          $('.vtabs a').each(function(i, v) {
            $select
            .append($("<option></option>")
            .attr("value", $(v).attr('data-content_id'))
            .text($(v).find('strong').text()));
          });
          
          // Show the filter section
          $('#module > thead > .filter').show();
          
          $('#module-row').val( Number(module_row) + 1);
          
          return false;
        });
        
        
        // Module filters
        $('#InstallmentPlanInfo').on('change keyup', '#module > thead > .filter :input',  function() {

          $('#module > tbody').hide();

          var is_filter_value = false;

          $('#module > thead > .filter').find(':input').each(function(i, v) {
            if ($(v).attr('data-class')) {
              if ($(v).val()) {
                is_filter_value = true;
                return false;
              }
            }
          });

          if (!is_filter_value) {
            $('#module > tbody').show();
            return false;
          }

          var arrays = [];

          $('#module > thead > .filter').find(':input').each(function(i, v) {
            var filter_value = $(v).val().toLowerCase();
            var elements = [];
            var _class = $(v).attr('data-class');
            if (_class) {
              var _filter_field_type = $(v).get(0).tagName.toLowerCase();

              $('#module').find(_class).each(function(j, k) {
                var _module_field_type = $(k).get(0).tagName.toLowerCase();

                var is_match = false;

                switch(_filter_field_type) {
                case 'input':
                  if (_module_field_type == 'input') {
                    if ($(k).val().toLowerCase().indexOf(filter_value) > -1) {
                      is_match = true;
                    }
                  } else if (_module_field_type == 'select') {
                    if ($.trim($(k).children('option:selected').text()).toLowerCase().indexOf(filter_value) > -1) {
                      is_match = true;
                    }
                  }
                  break;
                case 'select':
                  if (_module_field_type == 'select') {
                    if (filter_value == '*') {
                      is_match = true;
                    } else if ($.trim($(k).children('option:selected').val()).toLowerCase().indexOf(filter_value) > -1) {
                      is_match = true;
                    }
                  }          
                  break;
                }

                if (is_match) {
                  elements.push($(this).parents('tbody').attr('id'));
                }
              });
              arrays.push(elements);
            }
          });
          if (arrays.length > 0 ) {
            var result = arrays.shift().reduce(function(res, v) {
              if (res.indexOf(v) === -1 && arrays.every(function(a) {
                return a.indexOf(v) !== -1;
              })) res.push(v);
              return res;
            }, []);  

            $.each(result, function(i, v){
              $('#' + v).show();
            });  
          }
          return false;
        });
        
        
        $('#InstallmentPlanInfo').on('change', '.select-module-content-id',  function() {
          var content_id = $(this).val();
          var $tabs = $('.vtabs');
          var $tabLink = $tabs.find('a[data-content_id=\'' + content_id + '\']');

          if (content_id > 0) {
            $tabs.find('a').removeClass('selected');

            $tabs.find('a').each(function(i, element) {
              $($(element).attr('href')).hide();
            });

            $tabLink.addClass('selected');
            $($tabLink.attr('href')).show();
          }
        });        

        // Clear filters
        $('#module').find('#button-clear-filters').click(function() {
          $('#module > thead > .filter').find(':input').val('');
          $('#module > tbody').show();
          return false;
        });

        
        // Set the default state of the filter section.
        if ($('#module-row').val() > 0) {
          // Show the filter section
          $('#module').find('.filter').show();
        }
        
        
        // Remove button
        $('#module > tbody > tr > td > a').live('click', function() {
          
          // Update the value
          $('#module-row').val( Number($('#module-row').val()) - 1);

          if ($('#module-row').val() <= 0) {
            // Hide the filter section
            $('#module').find('.filter').hide();
          }
          
          // Remove the row
          $(this).closest('tbody').remove();
          
          return false;
        });
        
        
        $('a[data-redirect-after-save]').click(function() {
          var _value = $(this).attr('data-redirect-after-save');
          var _input = $("<input>").attr("type", "hidden").attr("name", "redirect_after_save").val(_value);
          $('#form').append($(_input)).submit();
          return false;
        });        
        
      },
  /**
   * showHideScrollBar method
   *
   * @param void
   * @return void
   */   
      showHideScrollBar: function () {
        $container = $('.tab-container');
        if ($container.find('a').length >= 14) {
          $container.css('height', '509px').css('margin-bottom', '5px').css('overflow-y', 'scroll');
          $container.addClass('tabs-scrollbar');
          $container.scrollTop($container[0].scrollHeight);
        } else {
          $container.css('height', '').css('margin-bottom', '0').css('overflow-y', 'hidden');
          $container.removeClass('tabs-scrollbar');
        }

        // This gets called on page load.
        if ($container.is(':hidden')) {
          $container.show();
        } 
      },
  /**
   * _bindTabToolTip method
   *
   * @param object $element
   * @return void
   */   
      _bindTabToolTip: function($element) {
        $element.powerTip({
          popupId: 'powerTip-vtabLink',
          mouseOnToPopup: true,
          placement: 'e', // East tooltip position
          fadeInTime: 100,
          fadeOutTime: 100,
          intentPollInterval: 200,
          offset: 5
        }).on({
          powerTipPreRender: function() {
            $(this).data('powertip', function() {
              if ($(this).find('strong')[0].scrollWidth > $(this).find('strong').width()) {
                return $(this).text(); 
              }
              return false;  
            });
          },
          powerTipOpen: function() {
            var $el = $(this);
            $el.powerTip('reposition');
          }
         });
      },
  /**
   * _bindInfoToolTip method
   *
   * @param object $element
   * @return void
   */   
      _bindInfoToolTip: function($element) {
        $element.powerTip({
          popupId: 'powerTip-info',
          mouseOnToPopup: true,
          placement: 'n', // East tooltip position
          fadeInTime: 200,
          fadeOutTime: 100,
          intentPollInterval: 300,
          offset: 0
        }).on({
          powerTipOpen: function() {
             var $el = $(this);
             $el.powerTip('reposition');
          }
         });        
      },
  /**
   * _bindInfoToolTip method
   *
   * example 1: range ( 0, 12 );
   * returns 1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
   * example 2: range( 0, 100, 10 );
   * returns 2: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
   * example 3: range( 'a', 'i' );
   * returns 3: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
   * example 4: range( 'c', 'a' );
   * returns 4: ['c', 'b', 'a']
   *
   * @param number low
   * @param number high
   * @param number step
   * @return array
   */ 
      range: function(low, high, step) {
        var matrix = [];
        var inival, endval, plus;
        var walker = step || 1;
        var chars = false;

        if (!isNaN(low) && !isNaN(high)) {
          inival = low;
          endval = high;
        } else if (isNaN(low) && isNaN(high)) {
          chars = true;
          inival = low.charCodeAt(0);
          endval = high.charCodeAt(0);
        } else {
          inival = (isNaN(low) ? 0 : low);
          endval = (isNaN(high) ? 0 : high);
        }

        plus = ((inival > endval) ? false : true);
        if (plus) {
          while (inival <= endval) {
            matrix.push(((chars) ? String.fromCharCode(inival) : inival));
            inival += walker;
          }
        } else {
          while (inival >= endval) {
            matrix.push(((chars) ? String.fromCharCode(inival) : inival));
            inival -= walker;
          }
        }

        return matrix;
      }      

    }
  }); 
  
  $.fn.extend({
    installmentPlanInfo: function(settings) {
      return $.installmentPlanInfo.init(this, settings);
    }
  });  

})(jQuery);