public function createConfigForm(Am_Grid_Editable $grid)
    {
        $form = new Am_Form_Admin();
        $record = $grid->getRecord($grid->getCurrentAction());
        if (empty($record->type)) {
            $record->type = null;
        }
        if (empty($record->tier)) {
            $record->tier = 0;
        }
        $globalOptions = AffCommissionRule::getTypes();
        $record->type && !isset($globalOptions[$record->type]) && ($globalOptions[$record->type] = $record->getTypeTitle());
        $cb = $form->addSelect('type')->setLabel('Type')->loadOptions($globalOptions);
        if ($record->isGlobal()) {
            $cb->toggleFrozen(true);
        }
        $form->addScript()->setScript(<<<CUT
\$(function(){
    \$("select#type-0").change(function(){
        var val = \$(this).val();
        \$("fieldset#multiplier").toggle(val == 'multi');
        \$("fieldset#commission").toggle(val != 'multi');
        var checked = val.match(/^global-/);
        \$("#conditions").toggle(!checked);
        \$("#sort_order-0").closest(".row").toggle(!checked);
    }).change();

    \$("#condition-select").change(function(){
        var val = \$(this).val();
        \$(this.options[this.selectedIndex]).prop("disabled", true);
        this.selectedIndex = 0;
        \$('input[name="_conditions_status[' + val + ']"]').val(1);
        \$('#row-'+val).show();
    });

    \$("#conditions .row").not("#row-condition-select").each(function(){
        var val = /row-(.*)/i.exec(this.id).pop();
        if (!\$('input[name="_conditions_status[' + val + ']"]').val()) {
            \$(this).hide();
        } else {
            \$("#condition-select option[value='"+val+"']").prop("disabled", true);
        }
        \$(this).find(".element-title").append("&nbsp;<a href='javascript:' class='hide-row'>X</a>&nbsp;");
    });

    \$(document).on('click',"a.hide-row",function(){
        var row = \$(this).closest(".row");
        var id = row.hide().attr("id");
        var val = /row-(.*)/i.exec(id).pop();
        \$('input[name="_conditions_status[' + val + ']"]').val(0);
        \$("#condition-select option[value='"+val+"']").prop("disabled", false);
    });

    \$('#used-type').change(function(){
        \$('#used-batch_id, #used-code').hide();
        switch (\$(this).val()) {
            case 'batch' :
                \$('#used-batch_id').show();
                break;
            case 'coupon' :
                \$('#used-code').show();
                break;
        }

    }).change()
});
CUT
);
        $comment = $form->addText('comment', array('size' => 40))->setLabel('Rule title - for your own reference');
        if ($record->isGlobal()) {
            $comment->toggleFrozen(true);
        } else {
            $comment->addRule('required', 'This field is required');
        }
        if (!$record->isGlobal()) {
            $form->addInteger('sort_order')->setLabel('Sort order - rules with lesser values executed first');
        }
        if (!$record->isGlobal()) {
            $set = $form->addFieldset('', array('id' => 'conditions'))->setLabel('Conditions');
            $set->addSelect('', array('id' => 'condition-select'))->setLabel('Add Condition')->loadOptions(array('' => ___('Select Condition...'), 'first_time' => ___('First Time Purchase of Product'), 'coupon' => ___('By Used Coupon'), 'paysys_id' => ___('By Used Payment System'), 'product_id' => ___('By Product'), 'product_category_id' => ___('By Product Category'), 'aff_group_id' => ___('By Affiliate Group Id'), 'aff_sales_count' => ___('By Affiliate Sales Count'), 'aff_items_count' => ___('By Affiliate Item Sales Count'), 'aff_sales_amount' => ___('By Affiliate Sales Amount'), 'aff_product_id' => ___('By Affiliate Active Product'), 'aff_product_category_id' => ___('By Affiliate Active Product Category')));
            $set->addHidden('_conditions_status[product_id]');
            $set->addMagicSelect('_conditions[product_id]', array('id' => 'product_id'))->setLabel(___("This rule is for particular products\n" . 'if none specified, rule works for all products'))->loadOptions(Am_Di::getInstance()->productTable->getOptions());
            $set->addHidden('_conditions_status[product_category_id]');
            $el = $set->addMagicSelect('_conditions[product_category_id]', array('id' => 'product_category_id'))->setLabel(___("This rule is for particular product categories\n" . "if none specified, rule works for all product categories"));
            $el->loadOptions(Am_Di::getInstance()->productCategoryTable->getAdminSelectOptions());
            $set->addHidden('_conditions_status[aff_group_id]');
            $el = $set->addMagicSelect('_conditions[aff_group_id]', array('id' => 'aff_group_id'))->setLabel(___("This rule is for particular affiliate groups\n" . "you can add user groups and assign it to customers in User editing form"));
            $el->loadOptions(Am_Di::getInstance()->userGroupTable->getSelectOptions());
            $set->addHidden('_conditions_status[aff_sales_count]');
            $gr = $set->addGroup('_conditions[aff_sales_count]', array('id' => 'aff_sales_count'))->setLabel(___("Affiliate sales count\n" . "trigger this commission if affiliate made more than ... sales within ... days before the current date\n" . "(only count of new invoices is calculated)"));
            $gr->addStatic()->setContent('use only if affiliate referred ');
            $gr->addInteger('count', array('size' => 4));
            $gr->addStatic()->setContent(' invoices within last ');
            $gr->addInteger('days', array('size' => 4));
            $gr->addStatic()->setContent(' days');
            $set->addHidden('_conditions_status[aff_items_count]');
            $gr = $set->addGroup('_conditions[aff_items_count]', array('id' => 'aff_items_count'))->setLabel(___("Affiliate items count\n" . "trigger this commission if affiliate made more than ... item sales within ... days before the current date\n" . "(only count of items in new invoices is calculated"));
            $gr->addStatic()->setContent('use only if affiliate made ');
            $gr->addInteger('count', array('size' => 4));
            $gr->addStatic()->setContent(' item sales within last ');
            $gr->addInteger('days', array('size' => 4));
            $gr->addStatic()->setContent(' days');
            $set->addHidden('_conditions_status[aff_sales_amount]');
            $gr = $set->addGroup('_conditions[aff_sales_amount]', array('id' => 'aff_sales_amount'))->setLabel(___("Affiliate sales amount\n" . "trigger this commission if affiliate made more than ... sales within ... days before the current date\n" . "(only new invoices calculated)"));
            $gr->addStatic()->setContent('use only if affiliate made ');
            $gr->addInteger('count', array('size' => 4));
            $gr->addStatic()->setContent(' ' . Am_Currency::getDefault() . ' in commissions within last ');
            $gr->addInteger('days', array('size' => 4));
            $gr->addStatic()->setContent(' days');
            $set->addHidden('_conditions_status[coupon]');
            $gr = $set->addGroup('_conditions[coupon]', array('id' => 'coupon'))->setLabel(___('Used coupon'));
            $gr->setSeparator(' ');
            $gr->addSelect('used')->loadOptions(array('1' => 'Used', '0' => "Didn't Use"));
            $gr->addSelect('type')->setId('used-type')->loadOptions(array('any' => ___('Any Coupon'), 'batch' => ___("Coupon From Batch"), 'coupon' => ___("Specific Coupon")));
            $gr->addSelect('batch_id')->setId('used-batch_id')->loadOptions($this->getDi()->couponBatchTable->getOptions());
            $gr->addText('code', array('size' => 10))->setId('used-code');
            $set->addHidden('_conditions_status[paysys_id]');
            $set->addMagicSelect('_conditions[paysys_id]', array('id' => 'paysys_id'))->setLabel(___('This rule is for particular payment system'))->loadOptions(Am_Di::getInstance()->paysystemList->getOptions());
            $set->addHidden('_conditions_status[first_time]');
            $set->addStatic('_conditions[first_time]', array('id' => 'first_time'))->setLabel(___("First Time Purchase of Product"))->setContent("<div><strong>&#x2713;</strong></div>");
            $set->addHidden('_conditions_status[aff_product_id]');
            $set->addMagicSelect('_conditions[aff_product_id]', array('id' => 'aff_product_id'))->setLabel(___("Apply this rule if affiliate has active access to"))->loadOptions(Am_Di::getInstance()->productTable->getOptions());
            $set->addHidden('_conditions_status[aff_product_category_id]');
            $el = $set->addMagicSelect('_conditions[aff_product_category_id]', array('id' => 'aff_product_category_id'))->setLabel(___("Apply this rule if affiliate has active access to"));
            $el->loadOptions(Am_Di::getInstance()->productCategoryTable->getAdminSelectOptions());
        }
        $set = $form->addFieldset('', array('id' => 'commission'))->setLabel('Commission');
        if ($record->tier == 0) {
            $set->addElement(new Am_Form_Element_AffCommissionSize(null, null, 'first_payment'))->setLabel(___("Commission for First Payment\ncalculated for first payment in each invoice"));
            $set->addElement(new Am_Form_Element_AffCommissionSize(null, null, 'recurring'))->setLabel(___("Commission for Rebills"));
            $group = $set->addGroup('')->setLabel(___("Commission for Free Signup\ncalculated for first customer invoice only"));
            $group->addText('free_signup_c', array('size' => 5));
            $group->addStatic()->setContent('&nbsp;&nbsp;' . Am_Currency::getDefault());
            //->addRule('gte', 'Value must be a valid number > 0, or empty (no text)', 0);
        } else {
            $set->addText('first_payment_c')->setLabel(___("Commission\n% of commission received by referred affiliate"));
        }
        if (!$record->isGlobal()) {
            $set = $form->addFieldset('', array('id' => 'multiplier'))->setLabel('Multipier');
            $set->addText('multi', array('size' => 5, 'placeholder' => '1.0'))->setLabel(___("Multiply commission calculated by the following rules\n" . "to number specified in this field. To keep commission untouched, enter 1 or delete this rule"));
            //->addRule('gt', 'Values must be greater than 0.0', 0.0);
        }
        return $form;
    }
    public function createConfigForm(Am_Grid_Editable $grid)
    {
        $form = new Am_Form_Admin();
        $record = $grid->getRecord($grid->getCurrentAction());
        if (empty($record->type)) {
            $record->type = null;
        }
        $globalOptions = AffCommissionRule::getTypes();
        foreach (Am_Di::getInstance()->db->selectCol("SELECT DISTINCT `type` FROM ?_aff_commission_rule") as $type) {
            if (AffCommissionRule::isGlobalType($type) && $type != $record->type) {
                unset($globalOptions[$type]);
            }
        }
        $cb = $form->addSelect('type')->setLabel('Type')->loadOptions($globalOptions);
        if ($record->isGlobal()) {
            $cb->toggleFrozen(true);
        }
        $form->addScript()->setScript(<<<CUT
\$(function(){
    \$("select#type-0").change(function(){
        var val = \$(this).val();
        \$("fieldset#multiplier").toggle(val == 'multi');
        \$("fieldset#commission").toggle(val != 'multi');
        var checked = val.match(/^global-/);
        \$("#conditions").toggle(!checked);
        \$("#sort_order-0").closest(".row").toggle(!checked);
        \$("#comment-0").closest(".row").toggle(!checked);
    }).change();
    
    \$("#condition-select").change(function(){
        var val = \$(this).val();
        \$(this.options[this.selectedIndex]).prop("disabled", true);
        this.selectedIndex = 0;
        \$('#'+val).show();
    });

    \$("#conditions .row").not("#row-condition-select").each(function(){
        if (!\$(":input:filled", this).not(".magicselect").length && !\$(".magicselect-item", this).length) 
            \$(this).hide();
        else
            \$("#condition-select option[value='"+this.id+"']").prop("disabled", true);
        \$(this).find(".element-title").append("&nbsp;<a href='javascript:' class='hide-row'>X</a>&nbsp;");
    });

    \$("a.hide-row").live('click',function(){
        var row = \$(this).closest(".row");
        row.find("a.hide-row").remove();
        var id = row.hide().attr("id");
        \$("#condition-select option[value='"+id+"']").prop("disabled", false);
    });
});
CUT
);
        $form->addText('comment', array('size' => 40))->setLabel('Rule title - for your own reference')->addRule('required', 'This field is required');
        $form->addInteger('sort_order')->setLabel('Sort order - rules with lesser values executed first');
        if (!$record->isGlobal()) {
            $set = $form->addFieldset('', array('id' => 'conditions'))->setLabel('Conditions');
            $set->addSelect('', array('id' => 'condition-select'))->setLabel('Add Condition')->loadOptions(array('' => 'Select Condition...', 'row-product_id' => 'By Product', 'row-product_category_id' => 'By Product Category', 'row-aff_group_id' => 'By Affiliate Group Id', 'row-aff_sales_count' => 'By Affiliate Sales Count', 'row-aff_sales_amount' => 'By Affiliate Sales Amount'));
            $set->addMagicSelect('_conditions[product_id]', array('id' => 'product_id'))->setLabel(array('This rule is for particular products', 'if none specified, rule works for all products'))->loadOptions(Am_Di::getInstance()->productTable->getOptions());
            $el = $set->addMagicSelect('_conditions[product_category_id]', array('id' => 'product_category_id'))->setLabel(array('This rule is for particular product categories', 'if none specified, rule works for all product categories'));
            $el->loadOptions(Am_Di::getInstance()->productCategoryTable->getAdminSelectOptions());
            $el = $set->addMagicSelect('_conditions[aff_group_id]', array('id' => 'aff_group_id'))->setLabel(array('This rule is for particular affiliate groups', 'you can add user groups and assign it to customers in User editing form'));
            $el->loadOptions(Am_Di::getInstance()->userGroupTable->getSelectOptions());
            $gr = $set->addGroup('_conditions[aff_sales_count]', array('id' => 'aff_sales_count'))->setLabel(array('Affiliate sales count', 'trigger this commission if affiliate made more than ... sales within ... days before the current date' . PHP_EOL . '(recurring: affiliate sales count will be recalculated on each rebill)'));
            $gr->addStatic()->setContent('use only if affiliate made ');
            $gr->addInteger('count', array('size' => 4));
            $gr->addStatic()->setContent(' commissions within last ');
            $gr->addInteger('days', array('size' => 4));
            $gr->addStatic()->setContent(' days');
            $gr = $set->addGroup('_conditions[aff_sales_amount]', array('id' => 'aff_sales_amount'))->setLabel(array('Affiliate sales amount', 'trigger this commission if affiliate made more than ... sales within ... days before the current date' . PHP_EOL . '(recurring: affiliate sales count will be recalculated on each rebill)'));
            $gr->addStatic()->setContent('use only if affiliate made ');
            $gr->addInteger('count', array('size' => 4));
            $gr->addStatic()->setContent(' ' . Am_Currency::getDefault() . ' in commissions within last ');
            $gr->addInteger('days', array('size' => 4));
            $gr->addStatic()->setContent(' days');
        }
        $set = $form->addFieldset('', array('id' => 'commission'))->setLabel('Commission');
        if ($record->type != AffCommissionRule::TYPE_GLOBAL_2) {
            $set->addElement(new Am_Form_Element_AffCommissionSize(null, null, 'first_payment'))->setLabel(___("Commission for First Payment\ncalculated for first payment in each invoice"));
            $set->addElement(new Am_Form_Element_AffCommissionSize(null, null, 'recurring'))->setLabel(___("Commission for Rebills"));
            $set->addText('free_signup_c')->setLabel(___("Commission for Free Signup\ncalculated for first customer invoice only"));
            //->addRule('gte', 'Value must be a valid number > 0, or empty (no text)', 0);
        } else {
            $set->addText('first_payment_c')->setLabel(___("Second Level Commission\n% of commission received by referred affiliate"));
        }
        if (!$record->isGlobal()) {
            $set = $form->addFieldset('', array('id' => 'multiplier'))->setLabel('Multipier');
            $set->addText('multi', array('size' => 5, 'placeholder' => '1.0'))->setLabel(array(___("Multiply commission calculated by the following rules\n                    to number specified in this field. To keep commission untouched, enter 1 or delete this rule")));
            //->addRule('gt', 'Values must be greater than 0.0', 0.0);
        }
        return $form;
    }