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

addvarpayment = {};
addvarpayment.AddVariablePaymentInvoked = false;

addvarpayment.AddVariablePayment = function(selectedRecord){
    // Prevent this from being called twice
    if(addvarpayment.AddVariablePaymentInvoked){
        return;
    }
    
    Ext.onReady(function(){
        addvarpayment.defaultWidth = 150;
        
        // payment amount
        addvarpayment.paymentAmount = new Ext.form.TextField({
            id:               'paymentAmount',
            name:             'paymentAmount',
            fieldLabel:       lang("Payment Amount"),
            validationEvent:  false,
            width:            addvarpayment.defaultWidth,
            border:           false,
            value:            '',
            allowBlank:       false
        });
        
        addvarpayment.paymentAmountValidate = function(){
            if(addvarpayment.paymentAmount != undefined){
                if(addvarpayment.paymentAmount.getValue() != ""){
                    if(isNaN(addvarpayment.paymentAmount.getValue()) || addvarpayment.paymentAmount.getValue() < 0){
                        addvarpayment.paymentAmount.markInvalid('This field has a wrong format or is not valid');
                        return false;
                    }else{
                        addvarpayment.paymentAmount.clearInvalid();
                        return true;
                    }
                }else{
                    addvarpayment.paymentAmount.markInvalid('This field is required');
                    return false;
                }
            }else{
                return false;
            }
        }
        
        // payment reference
        addvarpayment.paymentReference = new Ext.form.TextField({
            id:               'paymentReference',
            name:             'paymentReference',
            fieldLabel:       lang("Pmt. Reference"),
            validationEvent:  false,
            width:            addvarpayment.defaultWidth,
            border:           false,
            value:            '',
            allowBlank:       true
        });
        
        // form
        addvarpayment.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:        [
                new Ext.form.Label({
                    fieldLabel: lang("Balance Due"),
                    text:       selectedRecord.data.simplebalancedue
                }),
                addvarpayment.paymentAmount,
                addvarpayment.paymentReference
            ]
        });
        
        //addvarpayment.simpleForm.render(document.body);
        
        // Window
        addvarpayment.varPayWin = new Ext.Window({
            id:           "varPayWindow",
            y:            25,
            layout:       'fit',
            width:        350,
            autoHeight:   true,
            modal:        true,
            closeAction:  'close',
            title:        lang("Add variable payment to invoice")+" "+selectedRecord.data.invoiceid,
            plain:        true,
            shadow:       false,
            items:        [
                addvarpayment.simpleForm
            ],
            buttons:      [
                {
                    id:       'btnAddVarPay',
                    text:     lang("OK"),
                    disabled: false,
                    hidden:   false,
                    handler:  function(){
                        addvarpayment.sendVarPay();
                    }
                },
                {
                    text:     'Cancel',
                    handler:  function(){
                        addvarpayment.varPayWin.destroy();
                        
                        //get the grid if there is one
                        addvarpayment.grid = Ext.getCmp("invoices-grid");
                        addvarpayment.grid.enable();
                    }
                }
            ]
        });
        
        addvarpayment.startVarPayWindow = function(){
            addvarpayment.paymentAmount.reset();
            addvarpayment.paymentAmount.setValue('');
            
            addvarpayment.paymentReference.reset();
            addvarpayment.paymentReference.setValue('');
            
            addvarpayment.varPayWin.show();
            
            // NEED TO CLEAR THE INVALID MESSAGE OF THE "PAYMENTAMOUNT" FIELD BECAUSE IT CAN START WITH AN EMPTY VALUE
            addvarpayment.paymentAmount.clearInvalid();
            
            addvarpayment.paymentAmount.focus('',300);
        }
    });
    
    addvarpayment.sendVarPay = function (){
        if(addvarpayment.paymentAmountValidate()      //addvarpayment.paymentAmount.validate()
          && addvarpayment.paymentReference.validate()){
            
            Ext.Ajax.request({
                url: 'index.php?fuse=billing&action=Admin_ActOnInvoices',
                params: {
                    items:          selectedRecord.data.invoiceid,
                    itemstype:      'invoices',
                    actionbutton:   "addvariablepaymentbutton",
                    paymentamount:  addvarpayment.paymentAmount.getValue(),
                    checknum:       addvarpayment.paymentReference.getValue()
                },
                success:  function(xhr){
                    if(refreshProfileHeaderBalance != undefined
                      && refreshProfileHeaderBalance != null){
                        refreshProfileHeaderBalance();
                    }
                    
                    //refreshgrid
                    addvarpayment.grid = Ext.getCmp("invoices-grid");
                    if(addvarpayment.grid != null){
                        addvarpayment.grid.enable();
                        addvarpayment.grid.getStore().load({params:{start:0}});
                    }
                    
                    var data = Ext.util.JSON.decode(xhr.responseText);
                    
                    if(data.error){
                        //we do not need to repopulate the filters if there was a validation error
                        if(data.message){
                            msg(lang("There was an error performing this action") + "<br/>" + data.message);
                        }else{
                            msg(lang("There was an error performing this action"));
                        }
                    }else if(data.message){
                        msg(data.message);
                    }else{
                        msg(lang("Invoice(s) have been updated"));
                    }
                },
                failure:  function(xhr){
                    if(refreshProfileHeaderBalance != undefined
                      && refreshProfileHeaderBalance != null){
                        refreshProfileHeaderBalance();
                    }
                    
                    //refreshgrid
                    addvarpayment.grid = Ext.getCmp("invoices-grid");
                    if(addvarpayment.grid != null){
                        addvarpayment.grid.enable();
                        addvarpayment.grid.getStore().load({params:{start:0}});
                    }
                    
                    var timeoutText = '';
                    if(xhr.isTimeout){
                        timeoutText = '<br>timeout';
                    }
                }
            });
            
            addvarpayment.varPayWin.destroy();
        }else{
            addvarpayment.message = '';
            addvarpayment.newline = "<br>";
            
            if(!addvarpayment.paymentAmountValidate()){ //if(!addvarpayment.paymentAmount.validate()){
                if(addvarpayment.message != ''){
                    addvarpayment.message += addvarpayment.newline;
                }
                
                addvarpayment.message += lang("Payment Amount");
            }
            
            if(!addvarpayment.paymentReference.validate()){
                if(addvarpayment.message != ''){
                    addvarpayment.message += addvarpayment.newline;
                }
                
                addvarpayment.message += lang("Pmt. Reference");
            }
            
            if(addvarpayment.message != ''){
                Ext.MessageBox.alert(lang("Errors"), lang("The following form field(s) were incomplete or incorrect") + ":<br><br>" + addvarpayment.message + "<br><br>" + lang("Please complete or correct the form and submit again."));
                return;
            }
        }
    }
    
    addvarpayment.startVarPayWindow();
    
    addvarpayment.AddVariablePaymentInvoked = true;
}