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

var getCurrentTaxRule;
var taxFieldTaxValidate;

var defaultCountry;

var taxWin;
var taxFieldCountryCode;
var taxFieldAllCountries;
var taxFieldState;
var taxFieldAll;
var taxFieldName;
var taxFieldLevel;
var taxFieldCompound;
var taxFieldCompoundContainer;
var taxFieldVat;
var taxFieldTax;

Ext.onReady(function(){
    
    var defaultWidth = 150;
    
//  countrycode
    var countrystore = new Ext.data.JsonStore({
        id:             "countrystore",
        root:           'countries',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
                            filter: "",
                            customerid: "0"
                        },
        fields:         [
                            'iso',
                            'name'
                        ],
        proxy:          new Ext.data.HttpProxy({
                            url:  'index.php?fuse=admin&action=Admin_GetCountryList'
                        })
    });
    
    countrystore.setDefaultSort('id', 'asc');
    
    countrystore.load();
    
    defaultCountry = 'US';
    
    taxFieldCountryCode = new Ext.form.ComboBox({
        id:               'taxFieldCountryCode',
        name:             'taxFieldCountryCode',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Country"),
        store:            countrystore,
        valueField:       'iso',
        displayField:     'name',
        value:            defaultCountry,
        hiddenId:         'taxFieldCountryCodeValue',
        hiddenName:       'taxFieldCountryCodeValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
    taxFieldCountryCode.on('select', toggledisableallCountryCode);
    
    function toggledisableallCountryCode(){
        if(taxFieldCountryCode.getValue() == '_ALL'){
            taxFieldAllCountries.setValue(true);
        }
    }
    
//  allcountries
    taxFieldAllCountries = new Ext.form.Checkbox({
        id:               'taxFieldAllCountries',
        name:             'taxFieldAllCountries',
        value:            true,
        validationEvent:  false,
        hideLabel:        true,
        boxLabel :        lang('All')
    });
    
    taxFieldAllCountries.on('check', toggledisableall);
    
    function toggledisableall()
    {
        if(taxFieldAllCountries.getValue()){
            taxFieldCountryCode.disable();
            taxFieldCountryCode.setValue('_ALL');
            
            taxFieldAll.disable();
            taxFieldAll.setValue(true);
        }else{
            taxFieldCountryCode.enable();
            taxFieldCountryCode.setValue(defaultCountry);
            
            taxFieldAll.enable();
            taxFieldAll.setValue(false);
        }
    }
    
//  state
    taxFieldState = new Ext.form.TextField({
        id:               'taxFieldState',
        name:             'taxFieldState',
        fieldLabel:       lang("State"),
        validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        value:            '',
        allowBlank:       false
    });
    
//  all
    taxFieldAll = new Ext.form.Checkbox({
        id:               'taxFieldAll',
        name:             'taxFieldAll',
        value:            true,
        validationEvent:  false,
        hideLabel:        true,
        boxLabel :        lang('All')
    });
    
    taxFieldAll.on('check', toggledisablestate);
    
    function toggledisablestate()
    {
        if(taxFieldAll.getValue()){
            taxFieldState.disable();
            taxFieldState.setValue(lang('All States'));
        }else{
            taxFieldState.enable();
            taxFieldState.setValue('');
            taxFieldState.clearInvalid();
        }
    }
    
//  name
    taxFieldName = new Ext.form.TextField({
        id:               'taxFieldName',
        name:             'taxFieldName',
        fieldLabel:       lang("Tax Name"),
        validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        value:            '',
        allowBlank:       false
    });
    
//  level
    taxFieldLevel = new Ext.form.ComboBox({
        id:               'taxFieldLevel',
        name:             'taxFieldLevel',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Tax Level"),
        store:            new Ext.data.ArrayStore({
                              idIndex:  0,
                              fields:   [
                                            'id',
                                            'levelname'
                                        ],
                              data:     [
                                            [
                                                1,
                                                1
                                            ],
                                            [
                                                2,
                                                2
                                            ]
                                        ]
                          }),
        valueField:       'id',
        displayField:     'levelname',
        value:            1,
        hiddenId:         'taxFieldLevelValue',
        hiddenName:       'taxFieldLevelValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
    taxFieldLevel.on('afterrender', hideShowCompound);
    taxFieldLevel.on('select', hideShowCompound);
    
//  compound
    taxFieldCompound = new Ext.form.ComboBox({
        id:               'taxFieldCompound',
        name:             'taxFieldCompound',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Compound"),
        store:            new Ext.data.ArrayStore({
                              idIndex:  0,
                              fields:   [
                                            'id',
                                            'compoundname'
                                        ],
                              data:     [
                                            [
                                                0,
                                                lang('No')
                                            ],
                                            [
                                                1,
                                                lang('Yes')
                                            ]
                                        ]
                          }),
        valueField:       'id',
        displayField:     'compoundname',
        value:            0,
        hiddenId:         'taxFieldCompoundValue',
        hiddenName:       'taxFieldCompoundValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
    taxFieldCompoundContainer = new Ext.Container({
        id:     'taxFieldCompoundContainer',
        layout: 'form',
        items : [
                    taxFieldCompound
                ],
        hidden: true
    });
    
    function hideShowCompound(){
        if(taxFieldCompoundContainer != undefined){
            if(taxFieldLevel.getValue() == 2){
                taxFieldCompoundContainer.show();
            }else{
                taxFieldCompoundContainer.hide();
                taxFieldCompound.setValue(0);
            }
        }
    }
    
//  vat
    taxFieldVat = new Ext.form.ComboBox({
        id:               'taxFieldVat',
        name:             'taxFieldVat',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Use VAT"),
        store:            new Ext.data.ArrayStore({
                              idIndex:  0,
                              fields:   [
                                            'id',
                                            'vatname'
                                        ],
                              data:     [
                                            [
                                                0,
                                                lang('No')
                                            ],
                                            [
                                                1,
                                                lang('Yes')
                                            ]
                                        ]
                          }),
        valueField:       'id',
        displayField:     'vatname',
        value:            0,
        hiddenId:         'taxFieldVatValue',
        hiddenName:       'taxFieldVatValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
//  tax
    taxFieldTax = new Ext.form.TextField({
        id:               'taxFieldTax',
        name:             'taxFieldTax',
        fieldLabel:       lang("Tax") + ' (%)',
        validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        value:            '',
        allowBlank:       false
    });
    
    taxFieldTaxValidate = function(){
        if(taxFieldTax != undefined){
            if(taxFieldTax.getValue() != ""){
                if(isNaN(taxFieldTax.getValue()) || taxFieldTax.getValue() < 0){
                    taxFieldTax.markInvalid('This field has a wrong format or is not valid');
                    return false;
                }else{
                    taxFieldTax.clearInvalid();
                    return true;
                }
            }else{
                taxFieldTax.markInvalid('This field is required');
                return false;
            }
        }else{
            return false;
        }
    }
    
// tabed 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:  .9,
                                              layout:       'form',
                                              border:       false,
                                              items:        [
                                                                taxFieldCountryCode,
                                                                taxFieldState
                                                            ]
                                          },
                                          {
                                              columnWidth:  .1,
                                              layout:       'form',
                                              border:       false,
                                              items:        [
                                                                taxFieldAllCountries,
                                                                taxFieldAll
                                                            ]
                                          }
                                      ]
                          },
                          taxFieldName,
                          taxFieldLevel,
                          taxFieldCompoundContainer,
                          taxFieldVat,
                          taxFieldTax
                      ]
    });
    
    //simpleForm.render(document.body);
    
// Window
    taxWin = new Ext.Window({
        id:           "taxWindow",
        y:            200,
        layout:       'fit',
        width:        350,
        autoHeight:   true,
        modal:        true,
        closeAction:  'hide',
        title:        lang("Add Tax Rule"),
        plain:        true,
        shadow:       false,
        items:        [simpleForm],
        buttons:      [
                          {
                              text:     'Close',
                              handler:  function(){
                                            taxWin.hide();
                                        }
                          },
                          {
                              id:       'btnAddTax',
                              text:     lang("Save"),
                              disabled: false,
                              hidden:   false,
                              handler:  function(){
                                            sendTax();
                                        }
                          }
                      ]
    });
    
    getCurrentTaxRule = function(action, id){
        var currentTaxRule = new Ext.data.JsonStore({
            id:             "currentEscalationRule",
            root:           'country',
            totalProperty:  'totalcount',
            idProperty:     'id',
            remoteSort:     true,
            baseParams:     {
                                defaultCountry: 1
                            },
            fields:         [
                                'defaultCountry'
                            ],
            proxy:          new Ext.data.HttpProxy({
                                url: 'index.php?fuse=admin&action=Admin_GetCountryList'
                            })
        });
        
        currentTaxRule.on('load',function(){
            record = currentTaxRule.getAt(0);
            
            defaultCountry = record.get('defaultCountry');
            
            taxFieldCountryCode.reset();
            taxFieldCountryCode.setValue(defaultCountry);
            
            taxFieldAllCountries.reset();
            taxFieldAllCountries.setValue(false);
            
            taxFieldState.reset();
            taxFieldState.setValue('');
            
            taxFieldAll.reset();
            taxFieldAll.setValue(false);
            
            taxFieldName.reset();
            taxFieldName.setValue('');
            
            taxFieldLevel.reset();
            taxFieldLevel.setValue(1);
            
            taxFieldCompound.reset();
            taxFieldCompound.setValue(0);
            
            hideShowCompound();
            
            taxFieldVat.reset();
            taxFieldVat.setValue(0);
            
            taxFieldTax.reset();
            taxFieldTax.setValue('');
            
            taxWin.show();
            
            // NEED TO CLEAR THE INVALID MESSAGE OF THE "TAXFIELDSTATE", "TAXFIELDNAME" AND "TAXFIELDTAX" FIELDS BECAUSE THEY CAN START WITH AN EMPTY VALUE
            taxFieldState.clearInvalid();
            taxFieldName.clearInvalid();
            taxFieldTax.clearInvalid();
            
            taxFieldCountryCode.focus(); // for some reason the focus get lost
        });
        
        currentTaxRule.load();
    }
});

function addTaxRule(){
    getCurrentTaxRule('add', 0);
}

function sendTax(){
    if(taxFieldCountryCode.validate()
      && taxFieldAllCountries.validate()
      && taxFieldState.validate()
      && taxFieldAll.validate()
      && taxFieldName.validate()
      && taxFieldLevel.validate()
      && taxFieldCompound.validate()
      && taxFieldVat.validate()
      && taxFieldTaxValidate()){ //&& taxFieldTax.validate()){
        new Ajax.Request('index.php?fuse=admin&action=AddTaxRules',
                         {parameters: 'countrycode='  + encodeURIComponent(taxFieldCountryCode.getValue())
                                   + '&allcountries=' + encodeURIComponent(taxFieldAllCountries.getValue())
                                   + '&state='        + encodeURIComponent(taxFieldState.getValue())
                                   + '&all='          + encodeURIComponent(taxFieldAll.getValue())
                                   + '&name='         + encodeURIComponent(taxFieldName.getValue())
                                   + '&level='        + encodeURIComponent(taxFieldLevel.getValue())
                                   + '&compound='     + encodeURIComponent(taxFieldCompound.getValue())
                                   + '&vat='          + encodeURIComponent(taxFieldVat.getValue())
                                   + '&tax='          + encodeURIComponent(taxFieldTax.getValue()),
                          onComplete: onCompleteAction
                         }
                        );
    }else{
        message = '';
        newline = "<br>";
        
        if(!taxFieldCountryCode.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Country");
        }
        
        if(!taxFieldAllCountries.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("All Countries");
        }
        
        if(!taxFieldState.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("State");
        }
        
        if(!taxFieldAll.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("All States");
        }
        
        if(!taxFieldName.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Tax Name");
        }
        
        if(!taxFieldLevel.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Tax Level");
        }
        
        if(!taxFieldCompound.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Compound");
        }
        
        if(!taxFieldVat.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Use VAT");
        }
        
        if(!taxFieldTaxValidate()){ //if(!taxFieldTax.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Tax") + ' (%)';
        }
        
        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"),"");
    }
    
    taxWin.hide();

    //get the grid if there is one
    //if we are in the tax rules view
    //if not then skip
    grid = Ext.getCmp("tax-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
}