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

var selectedCurrency;
var currencystore;
var currencyCode;
var simpleForm;

var CurrencyWin;

function ShowEditCurrencyWindow(id){
        CurrencyWin.CreateWindow(true);
        CurrencyWin.PopulateFields(id);
}

Ext.onReady(function(){
    var win;

    // create the combo instance
//    var alignmentcombo = new Ext.form.ComboBox({
//        typeAhead: false,
//        triggerAction: 'all',
//        lazyRender:true,
//        name: 'alignment',
//        hiddenId: 'alignmentValue',
//        hiddenName: 'alignmentValue',
//        width: 70,
//        store: new Ext.data.ArrayStore({
//            id: 'alignmentOptions',
//            name: 'alignmentOptions',
//            fields: [
//                'myId',
//                'displayText'
//            ],
//            data: [['left', lang('Left')], ['right', lang('Right')]]
//        }),
//        valueField: 'myId',
//        displayField: 'displayText',
//        value: 'left',
//        fieldLabel: lang('Alignment'),
//        allowBlank: false,
//        mode: 'local',
//        forceSelection: true,
//        editable: false
//    });

    selectedCurrency = '';

    currencystore = new Ext.data.JsonStore({
        id:             "currencystore",
        root:           'currenciescodes',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
                            filter: "",
                            customerid: "0",
                            code: selectedCurrency
                        },
        fields:         [
                            'code',
                            'name'
                        ],
        proxy:          new Ext.data.HttpProxy({
                            url:  'index.php?fuse=billing&action=GetCurrenciesCodes'
                        })
    });
    
    currencystore.setDefaultSort('id', 'asc');
    
    currencystore.load();
    
    currencyCode = new Ext.form.ComboBox({
        id:               'abrv',
        name:             'abrv',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            70,
        fieldLabel:       lang("Code"),
        store:            currencystore,
        valueField:       'code',
        displayField:     'code',
        value:            selectedCurrency,
        hiddenId:         'abrvValue',
        hiddenName:       'abrvValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false,
        listeners:        {
            select: function(combo,record,index){
                var elementObject = currencystore.getAt(index);
                simpleForm.getForm().findField('name').setValue(elementObject.data['name']);
            }
        }
    });

    //alert(editlinks.length);
    simpleForm = new Ext.FormPanel({
        labelWidth:   75, // label settings here cascade unless overridden
        frame:        true,
        border:       false,
        hideBorders:  true,
        bodyStyle:    'padding:8px 15px 0',
        width:        190,
        autoHeight:   true,
        defaults:     {width: 70},
        defaultType:  'textfield',
        items:        [
                          {
                              fieldLabel: 'Id',
                              id:         'id',
                              name:       'id',
                              xtype:      "hidden"
                          },
                          {
                              fieldLabel: lang('Name'),
                              id:         'name',
                              name:       'name',
                              allowBlank: false,
                              width:      150
                          },
//                          {
//                              fieldLabel: lang('Symbol'),
//                              name:       'symbol',
//                              allowBlank: false,
//                              width:      70
//                          },
//                          {
//                              fieldLabel: lang('Code'),
//                              name:       'abrv',
//                              allowBlank: false,
//                              width:      70
//                          },
//                          alignmentcombo,
//                          {
//                              fieldLabel: lang('Precision'),
//                              name:       'precision',
//                              allowBlank: false,
//                              width:      70
//                          }
                          currencyCode
                          /*
                          ,{
                              fieldLabel: lang('Rate'),
                              id:         'rate',
                              name:       'rate',
                              allowBlank: false,
                              width:      70
                          }
                          */
                      ]
    });

    simpleForm.on({
                      actioncomplete: function(f,a){
                                          if(a.type == 'load'){
                                              selectedCurrency = simpleForm.getForm().findField('abrv').getValue();
                                              currencystore.setBaseParam('code', selectedCurrency);
                                              currencystore.load();
                                              currencyCode.getStore().reload();
                                          }
                                      }
    });

    function TableTypeWindow(update){
        if(this instanceof TableTypeWindow){
            this.update = update;
            this.CreateWindow = createWindow;
            this.PopulateFields = populateFields;
        }else{
            return new TableTypeWindow();
        }
    }
    CurrencyWin = new TableTypeWindow();

    function populateFields(id){
        geturl = 'index.php?fuse=admin&action=GetCurrencies&id=' + id;
        simpleForm.getForm().load({url:geturl, waitMsg:'Loading'});
    }

    function createWindow(update){
        if(update){
            requesturl = 'index.php?fuse=billing&action=UpdateCurrency';
            buttonText = 'Update';
            titleText = '&nbsp;&nbsp;'+lang('Edit Currency');
        }else{
            requesturl = 'index.php?fuse=billing&action=AddCurrency';
            buttonText = 'Save';
            titleText = '&nbsp;&nbsp;'+lang('Add Currency');
        }

        // create the window on the first click and reuse on subsequent clicks
        //if(!win){
            win = new Ext.Window({
                layout:'fit',
                title:titleText,
                width:290,
                autoHeight:true,
                modal:true,
                closeAction:'hide',
                plain: true,
                items: [simpleForm],
                buttons: [
                    {
                    text: 'Close',
                    handler: function(){
                        win.hide();
                    }
                }]
            });

            // simple button save (update)
            win.addButton(buttonText, function(){
                simpleForm.getForm().submit({
                    clientValidation: true,
                    url: requesturl,
                    params: {
                        newStatus: 'delivered'
                    },
                    success: function(form, action) {
                       win.hide();
                       //get the grid if there is one
                       //if we are in the currency view
                       //if not then skip
                       grid = Ext.getCmp("currency-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

                    },
                    failure: function(form, action) {
                        switch (action.failureType) {
                            case Ext.form.Action.CLIENT_INVALID:
                                Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                                break;
                            case Ext.form.Action.CONNECT_FAILURE:
                                Ext.Msg.alert('Failure', 'Ajax communication failed');
                                break;
                            case Ext.form.Action.SERVER_INVALID:
                               Ext.Msg.alert('Failure', action.result.msg);
                       }
                    }

                });
            });
        //}else{
        //    simpleForm.getForm().reset();
        //}

        win.show(this);
    }

    // option button code
    function toggleButtons(count){
        if(count == undefined){
            //get the sm if there is one
            //if we are in the currency view
            //if not then skip
            sm = Ext.getCmp("currency-sm");
            if(sm!=null){
                count = sm.getCount();
            }
        }
        if(count != undefined){
            //get the deletebutton if there is one
            //if we are in the currency view
            //if not then skip
            deletebutton = Ext.getCmp("actionbuttons");
            
            //get the setdefaultbutton if there is one
            //if we are in the currency view
            //if not then skip
            setdefaultbutton = Ext.getCmp("statusbuttons");
            
            if(count>0){
                if(deletebutton!=null){
                    deletebutton.setDisabled(false);
                }

                if(setdefaultbutton!=null){
                    if(count>1){
                        setdefaultbutton.setDisabled(true);
                    }else{
                        setdefaultbutton.setDisabled(false);
                    }
                }
            }else{
                if(deletebutton!=null){
                    deletebutton.setDisabled(true);
                }
                
                if(setdefaultbutton!=null){
                    setdefaultbutton.setDisabled(true);
                }
            }
        }
    }
});