var tree;
var selectedCustomField = -1;
var fieldForm;

Ext.onReady(function(){
    // shorthand
    var Tree = Ext.tree;
    
    var Tree_Loader = new Ext.tree.TreeLoader({
        dataUrl: 'index.php?fuse=admin&action=GetCustomFields',
        baseParams: {
            type: customFieldType
        }
    });
    
    Tree_Loader.on({
        load: function (treeloader, node, resp) {
            if (node.hasChildNodes()) {
               SelectCustomField(node.childNodes[0].id);
            }
        }
    });

    tree = new Tree.TreePanel({
        useArrows: true,
        autoScroll: true,
        animate: true,
        enableDD: true,
        containerScroll: true,
        border: true,
        loader: Tree_Loader,
        width:  250,
        height: 500,
        
        root: {
            nodeType: 'async',
            text: lang('(drag field to reorder)'),
            draggable: false,
            id: 'src'
        }
    });
    
    var extraItems;
    var customFieldTypeOptions;
    
    if (customFieldType == 'profile') {
    
        customFieldTypeOptions = [
            [0, lang('Text Field')],
            [1, lang('Yes/No')],
            [2, lang('Address Field')],
            [3, lang('City')],
            [4, lang('State / Prov')],
            [5, lang('Zip / Postal')],
            [6, lang('Country')],
            [7, lang('Phone')],
            [8, lang('Language')],
            [9, lang('Drop Down')],
            [10, lang('Text Area')],
            [11, lang('First Name')],
            [12, lang('Last Name')],
            [13, lang('Email')],
            [14, lang('Organization')],
            [16, lang('Announcement Opt-Out')],
            [47, lang('VAT Number')],
            [15, lang('Date')]
            ];
            
        extraItems = [
            new Ext.form.Checkbox({
                id: 'customfieldadminprofile',
                fieldLabel: lang('Include in admin profile'),
                name: 'customfieldadminprofile'
            }), new Ext.form.Checkbox({
                id: 'customfieldcustomerprofile',
                fieldLabel: lang('Include in customer profile'),
                name: 'customfieldcustomerprofile'
            })
        ];
    } else {
        customFieldTypeOptions = [
            [0, lang('Text Field')],
            [1, lang('Yes/No')],
            [6, lang('Country')],
            [9, lang('Drop Down')],
            [10, lang('Text Area')],
            [15, lang('Date')]
            ];
        var tip = lang("Select product group(s) which are not related with the custom field");
        extraItems =[{
            layout: "column",
            border: false,
            items:[
            {
                width:80,
                xtype:"label",
                text:lang('Exclude from these product groups')
            },
            {
                width:25,
                border: false,

                html: '<img src="../images/information-button.png" qtip="'+tip+'">'
            },
            {
                id: 'customfieldpackages',
                xtype: 'multiselect',
                //fieldLabel: lang('Exclude from these product groups'),
                name: 'customfieldpackages',
                width: 200,
                store: packageTypes
            }]
        }];
    }
    
    var fieldItems = [{
                id: 'customfieldname',
                fieldLabel: lang('Field Name'),
                name: 'customfieldname',
                width: 174,
                allowBlank:false
            },{
                id: 'customfieldsize',
                fieldLabel: lang('Size'),
                name: 'customfieldsize',
                xtype: 'hidden'
            }, new Ext.form.ComboBox({
                id: 'customfieldtype',
                fieldLabel: 'Type',
                width: 174,
                name: 'customfieldtype',
                store: new Ext.data.ArrayStore({
                    fields: ['id', 'type'],
                    data: customFieldTypeOptions 
                }),
                valueField: 'id',
                displayField: 'type',
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                selectOnFocus: true,
                listeners: {
                    'select': function (combo, record, index) {
                        if (fieldForm.getForm().findField('customfieldtype').getValue() == "14"){ // typeORGANIZATION
                            alert('WARNING:  You can only have one field set to Organization');
                            fieldForm.getForm().findField('customfieldtype').setValue(0);
                        }else if (fieldForm.getForm().findField('customfieldtype').getValue() == "12"){ // typeLASTNAME
                            alert('WARNING:  You can only have one field set to Last Name');
                            fieldForm.getForm().findField('customfieldtype').setValue(0);
                        }else if (fieldForm.getForm().findField('customfieldtype').getValue() == "11"){ // typeFIRSTNAME
                            alert('WARNING:  You can only have one field set to First Name');
                            fieldForm.getForm().findField('customfieldtype').setValue(0);
                        }else if (fieldForm.getForm().findField('customfieldtype').getValue() == "13"){ // typeEMAIL
                            alert('WARNING:  You can only have one field set to Email');
                            fieldForm.getForm().findField('customfieldtype').setValue(0);
                        }else if (fieldForm.getForm().findField('customfieldtype').getValue() == "8"){ // typeLANGUAGE
                            alert('WARNING:  You can only have one field set to Language');
                            fieldForm.getForm().findField('customfieldtype').setValue(0);
                        }else if (fieldForm.getForm().findField('customfieldtype').getValue() == "6"){ // typeCOUNTRY
                            if (customFieldType == 'profile') {
                                alert('WARNING:  You can only have one field set to Country');
                                fieldForm.getForm().findField('customfieldtype').setValue(0);
                            }
                        }else if (fieldForm.getForm().findField('customfieldtype').getValue() == "4"){ // typeSTATE
                            alert('WARNING:  You can only have one field set to State');
                            fieldForm.getForm().findField('customfieldtype').setValue(0);
                        }else if (fieldForm.getForm().findField('customfieldtype').getValue() == "47"){ // typeVATNUMBER
                            alert('WARNING:  You can only have one field set to VAT Number');
                            fieldForm.getForm().findField('customfieldtype').setValue(0);
                        }else if (fieldForm.getForm().findField('customfieldtype').getValue() == "16"){ // typeALLOWEMAIL
                            alert('WARNING:  You can only have one field set to Announcement Opt-Out');
                            fieldForm.getForm().findField('customfieldtype').setValue(0);
                        }
                        
                        hideShowOptionsField();
                    }
                }
            }), {
                id: 'customfieldoptions',
                fieldLabel: lang('Options'),
                name: 'customfieldoptions',
                disabled: true
            }, new Ext.form.Checkbox({
                id: 'customfieldrequired',
                fieldLabel: lang('Is Required'),
                name: 'customfieldrequired'
            }), new Ext.form.Checkbox({
                id: 'customfieldadminonly',
                fieldLabel: lang('Admin only'),
                name: 'customfieldadminonly'
            }), new Ext.form.Checkbox({
                id: 'customfieldsignup',
                fieldLabel: lang('Include in Signup'),
                name: 'customfieldsignup'
            })
        ];

    // render the tree
    tree.render('customfields');
    tree.getRootNode().expand();
    
    tree.on({
      click: function (node) {
        SelectCustomField(node.id);
      },
      movenode: function(tree,node,oldParent,newParent,index){
          ReorderFields(oldParent);
      }
    });
    
    fieldForm = new Ext.FormPanel({
        labelWidth: 100, // label settings here cascade unless overridden
        url:'index.php?fuse=admin&action=UpdateCustomField&type=customFieldType',
        bodyStyle:'padding:15px 15px 0',
        width: 400,
        height: 500,
        defaultType: 'textfield',

        items: [{
            xtype:'fieldset',
            checkboxToggle:false,
            title: 'Field Information',
            autoHeight:true,
            defaultType: 'textfield',
            items: fieldItems
        },{
            xtype:'fieldset',
            checkboxToggle:false,
            title: 'Extra Information',
            autoHeight:true,
            //defaultType: 'textfield',
            items: extraItems
        }],

        buttons: [{
            text: lang('Save'),
            handler  : function() {
                SaveCustomField(); 
            }
        },{
            id: 'customfielddelete',
            text: lang('Delete'),
            handler  : function() {
                DeleteCustomField(selectedCustomField); 
            }
        }]
    });
    
    fieldForm.render('customfieldform');
    
    // Hack to hide a form field until needed
    Ext.getCmp('customfieldoptions').setDisabled(true);
    $('customfieldoptions').value = '';
    $('customfieldoptions').parentNode.parentNode.style.display = 'none';
});

function DeleteCustomField(id)
{
    if (id == 'src' || id == '-1') return;
    var post;
    post = "customfieldid=" + id;
    post += "&type=" + customFieldType;

    new Ajax.Request(   'index.php?fuse=admin&action=DeleteCustomField',
        {
            postBody    : post,
            onSuccess   : DeleteCustomFieldSuccess
        }
    );
}

function DeleteCustomFieldSuccess(t)
{
    tree.root.reload();
}

function SaveCustomField()
{

    if (selectedCustomField == '-1') return;
    
    // trick to ensure that all fields get populated
    disableOrEnableFields(1);
    
    var post;
    post = "customfieldid=" + selectedCustomField;
    post += "&type=" + customFieldType;
    // need to get dropdown values this way since getValues is dumb and posts the text?!
    post += "&customfieldtypevalue=" + fieldForm.getForm().findField('customfieldtype').getValue();
    post += "&" + fieldForm.getForm().getValues(true);
    
    new Ajax.Request(   'index.php?fuse=admin&action=SaveCustomField',
        {
            postBody    : post,
            onSuccess   : SaveCustomFieldSuccess
        }
    );
}

function SaveCustomFieldSuccess(t)
{
    tree.root.reload();
}

function SelectCustomField(id)
{
    if (id == 'src') return;
    selectedCustomField = id;
    
    // load the form with custom field details
    fieldForm.getForm().load({
        url: 'index.php?fuse=admin&action=GetCustomFieldInfo&customfieldid=' + id + '&type=' + customFieldType,
        success: function (form, action) {
            var json = Ext.util.JSON.decode(action.response.responseText);
            hideShowOptionsField();
            disableOrEnableFields(json.data.customfieldchangable);
        }
    }
    
    );
}

function ReorderFields(parent)
{
    // loop through all nodes to build the order
    var nodeIds = "";
    child = parent.firstChild;
    while (child != null) {
        nodeIds += child.id + ",";
        child = child.nextSibling;
    }
    
    var post = "type=" + customFieldType;
    post += "&fields=" + nodeIds;
    
    new Ajax.Request(   'index.php?fuse=admin&action=ReorderCustomFields',
        {
            postBody    : post,
            onSuccess   : SaveCustomFieldSuccess
        }
    );
}

// enable = 0 (disable fields)
// enable = 1 (enable fields)
// enable = 2 (like 0 but don't disable name)
function disableOrEnableFields(enable)
{
    if (enable == "0" || enable == "2") {
        if (enable == "0") fieldForm.getForm().findField('customfieldname').disable();
        fieldForm.getForm().findField('customfieldsize').disable();
        fieldForm.getForm().findField('customfieldtype').disable();
        fieldForm.getForm().findField('customfieldrequired').disable();
        if (customFieldType == 'profile') {
            fieldForm.getForm().findField('customfieldadminprofile').disable();    
            fieldForm.getForm().findField('customfieldcustomerprofile').disable();    
        }
        Ext.getCmp('customfielddelete').setDisabled(true);
    } else {
        fieldForm.getForm().findField('customfieldname').enable();
        fieldForm.getForm().findField('customfieldsize').enable();
        fieldForm.getForm().findField('customfieldtype').enable();
        fieldForm.getForm().findField('customfieldrequired').enable();
        if (customFieldType == 'profile') {
            fieldForm.getForm().findField('customfieldadminprofile').enable();    
            fieldForm.getForm().findField('customfieldcustomerprofile').enable();    
        }
        Ext.getCmp('customfielddelete').setDisabled(false);
    }
}

// checks for the dropdown custom field type
// and enables the dropdown options box if needed.
function hideShowOptionsField()
{
    if (fieldForm.getForm().findField('customfieldtype').getValue() == "9") {
        Ext.getCmp('customfieldoptions').setDisabled(false);
        $('customfieldoptions').parentNode.parentNode.style.display = '';
    } else {
        Ext.getCmp('customfieldoptions').setDisabled(true);
        $('customfieldoptions').parentNode.parentNode.style.display = 'none';
    }
}