/*
 * Ext JS Library 3.0 RC1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */

var getCurrentCoupon;
var couponFieldApplyToValidate;
var couponFieldDiscountValidate;
var couponFieldRecurringMonthsValidate;

var helpDiscount;

var couponWin;

var couponFieldCouponId;
var couponFieldName;
var couponFieldDescription;
var couponFieldCode;
var couponFieldQuantity;
var couponFieldDiscountType;
var couponFieldApplyTo;
var couponFieldApplyToContainer;
var couponFieldDiscount;
var couponFieldStartDate;
var couponFieldExpires;
var couponFieldRecurring;
var couponFieldRecurringMonths;
var couponFieldRecurringMonthsContainer;
var couponFieldTaxable;
var couponFieldAppliesTo;
var couponFieldBCycle;
var couponFieldArchive;

Ext.override(Ext.form.Field, {
    setFieldLabel:  function(text){
                        if(this.rendered){
                          this.el.up('.x-form-item', 10, true).child('.x-form-item-label').update(text);
                        }
                        
                        this.fieldLabel = text;
                    }
});

Ext.onReady(createCouponWin());

function createCouponWin(){
    var defaultWidth  = 250;
    
//  couponid
    couponFieldCouponId = new Ext.form.Hidden({
        id:               'couponFieldCouponId',
        name:             'couponFieldCouponId',
        value:            0,
        validationEvent:  false
    });
    
//  name
    couponFieldName = new Ext.form.TextField({
        id:               'couponFieldName',
        name:             'couponFieldName',
        fieldLabel:       lang("Coupon Name"),
        validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        value:            '',
        allowBlank:       false
    });
    
//  description
    couponFieldDescription = new Ext.form.TextArea({
        id:               'couponFieldDescription',
        name:             'couponFieldDescription',
        fieldLabel:       lang("Description"),
        border:           false,
        validationEvent:  false,
        width:            defaultWidth,
        height:           54,
        value:            ''
    });
    
//  code
    var helpCode = lang('Leave empty to autogenerate');
    
    couponFieldCode = new Ext.form.TextField({
        id:               'couponFieldCode',
        name:             'couponFieldCode',
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpCode.replace(/'/g, "&#39;") + "'>" + lang("Code") + "</span>",
        validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        value:            '',
        allowBlank:       true
    });
    
//  quantity
    var helpQuantity = lang('Leave empty for an unlimited number of coupons');
    
    couponFieldQuantity = new Ext.form.TextField({
        id:               'couponFieldQuantity',
        name:             'couponFieldQuantity',
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpQuantity.replace(/'/g, "&#39;") + "'>" + lang("Quantity") + "</span>",
        validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        value:            '',
        allowBlank:       true
    });
    
//  discount_type
    couponFieldDiscountType = new Ext.form.ComboBox({
        id:               'couponFieldDiscountType',
        name:             'couponFieldDiscountType',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Discount type"),
        store:            new Ext.data.ArrayStore({
                              idIndex:  0,
                              fields:   [
                                            'id',
                                            'discounttypename'
                                        ],
                              data:     [
                                            [
                                                'amount',
                                                lang("Amount")
                                            ],
                                            [
                                                'percentage',
                                                lang("Percentage")
                                            ]
                                        ]
                          }),
        valueField:       'id',
        displayField:     'discounttypename',
        value:            'amount',
        hiddenId:         'couponFieldDiscountTypeValue',
        hiddenName:       'couponFieldDiscountTypeValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });

    couponFieldDiscountType.on('afterrender', showDiscountTypeFields);
    couponFieldDiscountType.on('select', showDiscountTypeFields);
    
    function showDiscountTypeFields(){
        hideShowApplyTo();
        discountSymbol();
    }
    
//  applyTo
    couponFieldApplyTo = new Ext.ux.form.LovCombo({
        id:               'couponFieldApplyTo',
        name:             'couponFieldApplyTo',
        fieldLabel:       lang("Apply coupon to"),
        validationEvent:  false,
        width:            defaultWidth,
        hideOnSelect:     true,
        //hidden :          true,
        maxHeight:        200,
        allowBlank:       false,
        store:            new Ext.data.ArrayStore({
                              idIndex:  0,
                              fields:   [
                                            'id',
                                            'applytoname'
                                        ],
                              data:     [
                                            [
                                                'domainRegistration',
                                                lang("Domain Name Registration")
                                            ],
                                            [
                                                'domainTransfer',
                                                lang("Domain Name Transfer")
                                            ],
                                            [
                                                'package',
                                                lang("Package")
                                            ],
                                            [
                                                'packageSetup',
                                                lang("Package Setup")
                                            ],
                                            [
                                                'addons',
                                                lang("Package Add-ons")
                                            ],
                                            [
                                                'addonsSetup',
                                                lang("Package Add-ons Setup")
                                            ],
                                            [
                                                'other',
                                                lang("Other invoice items")
                                            ]
                                        ]
                          }),
        valueField:       'id',
        displayField:     'applytoname',
        value:            'domainRegistration,domainTransfer,package,packageSetup,addons,addonsSetup,other',
        triggerAction:    'all',
        mode:             'local',
        beforeBlur:       Ext.emptyFn
    });
    
    couponFieldApplyToContainer = new Ext.Container({
        id:     'couponFieldApplyToContainer',
        layout: 'form',
        items : [
                    couponFieldApplyTo
                ],
        hidden: true
    });
    
    function hideShowApplyTo(){
        if(couponFieldApplyToContainer != undefined){
            if(couponFieldDiscountType.getValue() == 'percentage'){
                couponFieldApplyToContainer.show();
            }else{
                couponFieldApplyToContainer.hide();
            }
        }
    }
    
    couponFieldApplyToValidate = function(){
        if(couponFieldDiscountType != undefined
          && couponFieldDiscountType.getValue() == 'percentage'){
            if(couponFieldApplyTo != undefined){
                if(couponFieldApplyTo.getValue() != ''){
                    couponFieldApplyTo.clearInvalid();
                    return true;
                }else{
                    couponFieldApplyTo.markInvalid('This field is required');
                    return false;
                }
            }else{
                return false;
            }
        }else{
            if(couponFieldApplyTo != undefined){
                couponFieldApplyTo.clearInvalid();
            }
            
            return true;
        }
    }
    
//  discount
    helpDiscount = '<a href="javascript:void(0);" qtip="' + lang('($) - Symbol for US Dollar') + '" >$</a>';
    
    couponFieldDiscount = new Ext.form.TextField({
        id:               'couponFieldDiscount',
        name:             'couponFieldDiscount',
        fieldLabel:       lang("Discount") + " (<span style='text-decoration: underline; top: 0px;' class='tip-target'>" + helpDiscount.replace(/'/g, "&#39;") + '</span>)',
        validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        value:            '',
        allowBlank:       false
    });
    
    function discountSymbol(){
        if(couponFieldApplyToContainer != undefined){
            if(couponFieldDiscountType.getValue() == 'percentage'){
                couponFieldDiscount.setFieldLabel(lang("Discount") + " (%)");
            }else{
                couponFieldDiscount.setFieldLabel(lang("Discount") + " (<span style='text-decoration: underline; top: 0px;' class='tip-target'>" + helpDiscount + '</span>)');
            }
        }
    }
    
    couponFieldDiscountValidate = function(){
        if(couponFieldDiscount != undefined){
            if(couponFieldDiscount.getValue() != ""){
                if(isNaN(couponFieldDiscount.getValue()) || couponFieldDiscount.getValue() <= 0){
                    couponFieldDiscount.markInvalid('This field has a wrong format or is not valid');
                    return false;
                }else{
                    couponFieldDiscount.clearInvalid();
                    return true;
                }
            }else{
                couponFieldDiscount.markInvalid('This field is required');
                return false;
            }
        }else{
            return false;
        }
    }
    
//  start_date
    var valueStartDate = (new Date()).dateFormat('m/d/Y');
    
    couponFieldStartDate = new Ext.form.DateField({
        id:               'couponFieldStartDate',
        name:             'couponFieldStartDate',
        fieldLabel:       lang("Start Date"),
        validationEvent:  false,
        height:           "5px",
        selectOnFocus:    true,
        format:           'm/d/Y',
        value:            valueStartDate,
        allowBlank:       false
    });
    
//  expires
    var helpExpires = lang('Leave empty for a coupon that never expires');
    
    couponFieldExpires = new Ext.form.DateField({
        id:               'couponFieldExpires',
        name:             'couponFieldExpires',
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpExpires.replace(/'/g, "&#39;") + "'>" + lang("Expiration Date") + "</span>",
        validationEvent:  false,
        height:           "5px",
        selectOnFocus:    true,
        format:           'm/d/Y',
        value:            '',
        allowBlank:       true
    });
    
//  recurring
    var helpRecurring = lang('Recurring coupons will be applied on every periodic payment') + '. <br><br>' + lang('NOTICE: Recurring coupons will use the same billing cycle of the package, and will not be applied to any addons or domains registration with different billing cycles from the package, in future invoices.');
    
    couponFieldRecurring = new Ext.form.ComboBox({
        id:               'couponFieldRecurring',
        name:             'couponFieldRecurring',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpRecurring.replace(/'/g, "&#39;") + "'>" + lang("Recurring") + "</span>",
        store:            new Ext.data.ArrayStore({
                              idIndex:  0,
                              fields:   [
                                            'id',
                                            'recurringname'
                                        ],
                              data:     [
                                            [
                                                1,
                                                lang("Yes")
                                            ],
                                            [
                                                0,
                                                lang("No")
                                            ]
                                        ]
                          }),
        valueField:       'id',
        displayField:     'recurringname',
        value:            0,
        hiddenId:         'couponFieldRecurringValue',
        hiddenName:       'couponFieldRecurringValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
    couponFieldRecurring.on('afterrender', hideShowRecurringMonths);
    couponFieldRecurring.on('select', hideShowRecurringMonths);
    
//  recurringmonths
    var helpRecurringMonths = lang('Leave empty for a coupon that will be recurring forever.<br><br>For a coupon that will be recurring for a limited amount of time, enter the amount of months for this coupon to be recurring.<br><br>The amount of times the coupon will be used for the customer depends on the amount of months the coupon will be recurring and the billing cycle selected by the customer in signup.<br><br>For example, if the coupon will be recurring for 4 months and the customer selects a Quarterly Billing Cycle, then the coupon will be used 2 time: <br>- in the first payment. (0 months has passed).<br>- in the second payment. (3 months has passed).<br><br>In the third payment the coupon can not be used because 6 months has passed and the coupon only works for 4 months.');
    
    couponFieldRecurringMonths = new Ext.form.TextField({
        id:               'couponFieldRecurringMonths',
        name:             'couponFieldRecurringMonths',
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpRecurringMonths.replace(/'/g, "&#39;") + "'>" + lang("Duration") + ' (' + lang("months") + ')' + "</span>",
        validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        value:            '',
        allowBlank:       true
    });
    
    couponFieldRecurringMonthsContainer = new Ext.Container({
        id:     'couponFieldRecurringMonthsContainer',
        layout: 'form',
        items : [
                    couponFieldRecurringMonths
                ],
        hidden: true
    });
    
    function hideShowRecurringMonths(){
        if(couponFieldRecurringMonthsContainer != undefined){
            if(couponFieldRecurring.getValue() == 1){
                couponFieldRecurringMonthsContainer.show();
            }else{
                couponFieldRecurringMonthsContainer.hide();
            }
        }
    }
    
    couponFieldRecurringMonthsValidate = function(){
        if(couponFieldRecurringMonths != undefined){
            if(couponFieldRecurringMonths.getValue() != ""){
                if(couponFieldRecurringMonths.getValue().toString().search(/^[0-9]+$/) == 0){
                    couponFieldRecurringMonths.clearInvalid();
                    return true;
                }else{
                    couponFieldRecurringMonths.markInvalid('This field has a wrong format or is not valid');
                    return false;
                }
            }else{
                couponFieldRecurringMonths.clearInvalid();
                return true;
            }
        }else{
            return false;
        }
    }
    
//  taxable
    couponFieldTaxable = new Ext.form.ComboBox({
        id:               'couponFieldTaxable',
        name:             'couponFieldTaxable',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Apply coupon"),
        store:            new Ext.data.ArrayStore({
                              idIndex:  0,
                              fields:   [
                                            'id',
                                            'taxablename'
                                        ],
                              data:     [
                                            [
                                                1,
                                                lang("Before taxes")
                                            ],
                                            [
                                                0,
                                                lang("After taxes")
                                            ]
                                        ]
                          }),
        valueField:       'id',
        displayField:     'taxablename',
        value:            1,
        hiddenId:         'couponFieldTaxableValue',
        hiddenName:       'couponFieldTaxableValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
//  applies_to
    var packagesstore = new Ext.data.JsonStore({
        id:             "packagesstore",
        root:           'packages',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
                            filter: "",
                            customerid: "0"
                        },
        fields:         [
                            'packageId',
                            'packageName'
                        ],
        proxy:          new Ext.data.HttpProxy({
                            url:  'index.php?fuse=admin&action=GetPackageList'
                        })
    });
    
    packagesstore.setDefaultSort('id', 'asc');
    packagesstore.load();
    
    couponFieldAppliesTo = new Ext.ux.form.LovCombo({
        id:               'couponFieldAppliesTo',
        name:             'couponFieldAppliesTo',
        fieldLabel:       lang("Packages"),
        validationEvent:  false,
        width:            defaultWidth,
        hideOnSelect:     true,
        //hidden :          true,
        maxHeight:        200,
        allowBlank:       false,
        store:            packagesstore,
        valueField:       'packageId',
        displayField:     'packageName',
        value:            '',
        triggerAction:    'all',
        mode:             'local',
        beforeBlur:       Ext.emptyFn
    });
    
//  bcycle
    couponFieldBCycle = new Ext.ux.form.LovCombo({
        id:               'couponFieldBCycle',
        name:             'couponFieldBCycle',
        fieldLabel:       lang("Billing Cycles"),
        validationEvent:  false,
        width:            defaultWidth,
        hideOnSelect:     true,
        //hidden :          true,
        maxHeight:        200,
        allowBlank:       false,
        store:            new Ext.data.ArrayStore({
                              idIndex:  0,
                              fields:   [
                                            'id',
                                            'bcyclename'
                                        ],
                              data:     [
                                            [
                                                'all',
                                                lang("All")
                                            ],
                                            [
                                                1,
                                                lang("Monthly")
                                            ],
                                            [
                                                3,
                                                lang("Quarterly")
                                            ],
                                            [
                                                6,
                                                lang("Semiannually")
                                            ],
                                            [
                                                12,
                                                lang("Yearly")
                                            ],
                                            [
                                                24,
                                                lang("Every 2 Years")
                                            ],
                                            [
                                                0,
                                                lang("Setup Fee Only (No Recurring Fee)")
                                            ]
                                        ]
                          }),
        valueField:       'id',
        displayField:     'bcyclename',
        value:            '',
        triggerAction:    'all',
        mode:             'local',
        beforeBlur:       Ext.emptyFn
    });
    
//  archive
    couponFieldArchive = new Ext.form.Hidden({
        id:               'couponFieldArchive',
        name:             'couponFieldArchive',
        value:            0,
        validationEvent:  false
    });
    
//  form
    var simpleForm = new Ext.FormPanel({
        //labelAlign:   'top',
        frame:        true,
        hideBorders:  true,
        shadow:       false,
        floating:     false,
        autoHeight:   true,
        title:        '',
        bodyStyle:    'padding:5px 5px 0',
        width:        600,
        items:        [
                          {
                              layout: 'column',
                              border: false,
                              items:  [
                                          {
                                              columnWidth:  1,
                                              layout:       'form',
                                              border:       false,
                                              items:        [
                                                                couponFieldCouponId,
                                                                couponFieldName,
                                                                couponFieldDescription,
                                                                couponFieldCode,
                                                                couponFieldQuantity,
                                                                couponFieldDiscountType,
                                                                couponFieldApplyToContainer,
                                                                couponFieldDiscount,
                                                                couponFieldStartDate,
                                                                couponFieldExpires,
                                                                couponFieldRecurring,
                                                                couponFieldRecurringMonthsContainer,
                                                                couponFieldTaxable,
                                                                couponFieldAppliesTo,
                                                                couponFieldBCycle,
                                                                couponFieldArchive
                                                            ]
                                          }
                                      ]
                          }
                      ]
    });
    
    //simpleForm.render(document.body);
    
//  Window
    couponWin = new Ext.Window({
        id:           "couponWindow",
        y:            200,
        layout:       'fit',
        width:        400,
        autoHeight:   true,
        modal:        true,
        //closeAction:  'close',
        closable:     false,
        title:        lang("Add Coupon"),
        plain:        true,
        shadow:       false,
        items:        [simpleForm],
        buttons:      [
                          {
                              text:     'Close',
                              handler:  function(){
                                            couponWin.hide();
                                            couponWin.destroy();
                                        }
                          },
                          {
                              id:       'btnAddCoupon',
                              text:     lang("Save"),
                              disabled: false,
                              hidden:   false,
                              handler:  function(){
                                            sendCoupon();
                                        }
                          }
                      ]
    });
    
    getCurrentCoupon = function(action, id){
        var currentCoupon = new Ext.data.JsonStore({
            id:             "currentCoupon",
            root:           'coupon',
            totalProperty:  'totalcount',
            idProperty:     'id',
            remoteSort:     true,
            baseParams:     {
                                id: id
                            },
            fields:         [
                                'couponid',
                                'name',
                                'description',
                                'code',
                                'quantity',
                                'discount_type',
                                'applyTo',
                                'discount',
                                'start_date',
                                'expires',
                                'recurring',
                                'recurringmonths',
                                'taxable',
                                'bcycle',
                                'applies_to',
                                'currencySymbol'
                            ],
            proxy:          new Ext.data.HttpProxy({
                                url: 'index.php?fuse=admin&action=GetCoupon'
                            })
        });
        
        currentCoupon.on('load',function(){
            record = currentCoupon.getAt(0);
            
            switch(action){
                case 'add':
                    couponWin.setTitle(lang("Add Coupon"));
                    break;
                case 'edit':
                    couponWin.setTitle(lang("Edit Coupon"));
                    break;
            }
            
            couponFieldCouponId.reset();
            couponFieldCouponId.setValue(record.get('couponid'));
            
            couponFieldName.reset();
            couponFieldName.setValue(record.get('name'));
            
            couponFieldDescription.reset();
            couponFieldDescription.setValue(record.get('description'));
            
            couponFieldCode.reset();
            couponFieldCode.setValue(record.get('code'));
            
            couponFieldQuantity.reset();
            couponFieldQuantity.setValue(record.get('quantity'));
            
            couponFieldDiscountType.reset();
            couponFieldDiscountType.setValue(record.get('discount_type'));
            
            couponFieldApplyTo.reset();
            couponFieldApplyTo.setValue(record.get('applyTo'));
            
            couponFieldDiscount.reset();
            couponFieldDiscount.setValue(record.get('discount'));
            
            couponFieldStartDate.reset();
            couponFieldStartDate.setValue(record.get('start_date'));
            
            couponFieldExpires.reset();
            couponFieldExpires.setValue(record.get('expires'));
            
            couponFieldRecurring.reset();
            couponFieldRecurring.setValue(record.get('recurring'));
            
            couponFieldRecurringMonths.reset();
            couponFieldRecurringMonths.setValue(record.get('recurringmonths'));
            
            couponFieldTaxable.reset();
            couponFieldTaxable.setValue(record.get('taxable'));
            
            couponFieldAppliesTo.reset();
            couponFieldAppliesTo.setValue(record.get('applies_to'));
            
            couponFieldBCycle.reset();
            couponFieldBCycle.setValue(record.get('bcycle'));
            
            helpDiscount = record.get('currencySymbol');
            
            showDiscountTypeFields();
            hideShowRecurringMonths();
            
            couponWin.show();
            
            // NEED TO CLEAR THE INVALID MESSAGE OF THE "COUPONFIELDNAME" AND "COUPONFIELDDISCOUNT" FIELDS BECAUSE THEY CAN START WITH AN EMPTY VALUE
            couponFieldName.clearInvalid();
            couponFieldDiscount.clearInvalid();
            
            couponFieldName.focus(); // for some reason the focus get lost
        });
        
        currentCoupon.load();
    }
}

function addCoupon(){
    createCouponWin();
    getCurrentCoupon('add', 0);
}

function editCoupon(id){
    createCouponWin();
    getCurrentCoupon('edit', id);
}

function sendCoupon(){
    if(couponFieldName.validate()
      && couponFieldDescription.validate()
      && couponFieldCode.validate()
      && couponFieldQuantity.validate()
      && couponFieldDiscountType.validate()
      && couponFieldApplyToValidate() //&& couponFieldApplyTo.validate()
      && couponFieldDiscountValidate() //&& couponFieldDiscount.validate()
      && couponFieldStartDate.validate()
      && couponFieldExpires.validate()
      && couponFieldRecurring.validate()
      && couponFieldRecurringMonthsValidate() //&& couponFieldRecurringMonths.validate()
      && couponFieldTaxable.validate()
      && couponFieldAppliesTo.validate()
      && couponFieldBCycle.validate()){
        new Ajax.Request('index.php?fuse=admin&action=SaveCoupon',
                         {parameters: 'couponid='        + encodeURIComponent(couponFieldCouponId.getValue())
                                   + '&name='            + encodeURIComponent(couponFieldName.getValue())
                                   + '&description='     + encodeURIComponent(couponFieldDescription.getValue())
                                   + '&code='            + encodeURIComponent(couponFieldCode.getValue())
                                   + '&quantity='        + encodeURIComponent(couponFieldQuantity.getValue())
                                   + '&discount_type='   + encodeURIComponent(couponFieldDiscountType.getValue())
                                   + '&applyTo='         + encodeURIComponent(couponFieldApplyTo.getValue())
                                   + '&discount='        + encodeURIComponent(couponFieldDiscount.getValue())
                                   + '&start_date='      + encodeURIComponent(couponFieldStartDate.getRawValue())
                                   + '&expires='         + encodeURIComponent(couponFieldExpires.getRawValue())
                                   + '&recurring='       + encodeURIComponent(couponFieldRecurring.getValue())
                                   + '&recurringmonths=' + encodeURIComponent(couponFieldRecurringMonths.getValue())
                                   + '&taxable='         + encodeURIComponent(couponFieldTaxable.getValue())
                                   + '&applies_to='      + encodeURIComponent(couponFieldAppliesTo.getValue())
                                   + '&bcycle='          + encodeURIComponent(couponFieldBCycle.getValue())
                                   + '&archive='         + encodeURIComponent(couponFieldArchive.getValue()),
                          onComplete: onCompleteAction
                         }
                        );
    }else{
        message = '';
        newline = "<br>";
        
        if(!couponFieldName.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Coupon Name");
        }
        
        if(!couponFieldDescription.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Description");
        }
        
        if(!couponFieldCode.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Code");
        }
        
        if(!couponFieldQuantity.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Quantity");
        }
        
        if(!couponFieldDiscountType.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Discount type");
        }
        
        if(!couponFieldApplyToValidate()){ //if(!couponFieldApplyTo.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Apply coupon to");
        }
        
        if(!couponFieldDiscountValidate()){ //if(!couponFieldDiscount.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Discount");
        }
        
        if(!couponFieldStartDate.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Start Date");
        }
        
        if(!couponFieldExpires.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Expiration Date");
        }
        
        if(!couponFieldRecurring.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Recurring");
        }
        
        if(!couponFieldRecurringMonthsValidate()){ //if(!couponFieldRecurringMonths.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Duration") + ' (' + lang("months") + ')';
        }
        
        if(!couponFieldTaxable.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Apply coupon");
        }
        
        if(!couponFieldAppliesTo.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Packages");
        }
        
        if(!couponFieldBCycle.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Billing Cycles");
        }
        
        if(message != ''){
            Ext.MessageBox.alert(lang("Errors"), lang("The following form field(s) were incomplete or incorrect") + ":<br><br>" + message + "<br><br>" + lang("Please complete or correct the form and submit again."));
            return;
        }
    }
}

function onCompleteAction(responseObj){
    var data = Ext.util.JSON.decode(responseObj.responseText);
    if(data.error){
        if(data.message){
            Ext.MessageBox.alert(lang("Errors"), data.message);
        }else{
            Ext.MessageBox.alert(lang("Errors"), "There was an error performing this action");
        }
        return;
    }else if(data.message){
        msg(data.message,"");
    }else{
        msg(lang("Action have been performed"),"");
    }
    
    couponWin.hide();
    couponWin.destroy();
    
    //get the grid if there is one
    //if we are in the coupons view
    //if not then skip
    grid = Ext.getCmp("coupon-grid");
    if(grid!=null){
        grid.getStore().load({params:{start:0}});
        //toggleButtons(0);
    }
    //we might want to check to see if we are showing a dropdown
    //in the event we are creating an invoice
    //do that code here and update the dropdown
}