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()) {
               tree.fireEvent('click',node.childNodes[0]);
               //showrightpanel
               $('#cffieldset1').removeClass( 'x-hide-display' );
               $('#cffieldset1').show();
               $('#cffieldset2').removeClass( 'x-hide-display' );
               $('#cffieldset2').show();
               $('#btnSave:parent').show();
               $('#customfielddelete:parent').show();
            } else {
               //hiderightpanel
               $('#cffieldset1').addClass( 'x-hide-display' );
               $('#cffieldset2').addClass( 'x-hide-display' );
               $('#btnSave:parent').hide();
               $('#customfielddelete:parent').hide();
            }
        }
    });

    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 the product group(s) you don't wish to show this custom field in.  You can select multiple groups by clicking on SELECT and then the mouse click.");
        extraItems =[
            {
                id: 'customfieldpackages',
                xtype: 'multiselect',
                fieldLabel: '<span style="cursor:pointer; border-bottom: 1px solid rgb(223, 223, 223);" qtip="'+tip+'">'+lang('Exclude from groups')+'</span>',
                name: 'customfieldpackages',
                labelStyle: 'width:124px;',
                style : {
                   paddingLeft: '22px'
                },
                width: 200,
                store: packageTypes
            }, new Ext.form.Checkbox({
                id: 'includetoproductidentifier',
                labelStyle: 'width:124px;',
                fieldLabel: '<span style="cursor:pointer; border-bottom: 1px solid rgb(223, 223, 223);" qtip="The value of this custom field will be used to help identify the product.">'+lang('Include in identifier')+'</span>',
                name: 'includetoproductidentifier'
            })
            ];
    }
    
    var fieldItems = [{
                id: 'customfieldname',
                fieldLabel: lang('Field Name'),
                name: 'customfieldname',
                labelStyle: 'width:124px;',
                width: 174,
                allowBlank:false
            },{
                id: 'customfielddesc',
                fieldLabel: lang('Field Description'),
                name: 'customfielddesc',
                labelStyle: 'width:124px;',
                width: 174,
                allowBlank:true
            },{
                id: 'customfieldsize',
                fieldLabel: lang('Size'),
                name: 'customfieldsize',
                xtype: 'hidden'
            }, new Ext.form.ComboBox({
                id: 'customfieldtype',
                fieldLabel: lang('Type'),
                labelStyle: 'width:124px;',
                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: '<span style="cursor:pointer; border-bottom: 1px solid rgb(223, 223, 223);" qtip="Please separate all drop down options by using a , between each value.<br />To have an option label be different from its value, enter the value between parenthesis, e.g.<br />red, brown(color_2), yellow">' + lang('Options') + '</span>',
                labelStyle: 'width:124px;',
                width: 174,
                name: 'customfieldoptions',
                disabled: true
            }, new Ext.form.Checkbox({
                id: 'customfieldrequired',
                fieldLabel: lang('Is Required'),
                labelStyle: 'width:124px;',
                name: 'customfieldrequired'
            }), new Ext.form.Checkbox({
                id: 'customfieldadminonly',
                fieldLabel: '<span style="cursor:pointer; border-bottom: 1px solid rgb(223, 223, 223);" qtip="This field is only visible by staff members and not visible to the customer when viewing their profile.">'+lang('Admin only')+'</span>',
                labelStyle: 'width:124px;',
                name: 'customfieldadminonly',
                listeners : {
                	'check' : function(cb,checked) {
                		if (checked) {
                			Ext.getCmp('customfieldreadonly').setDisabled(true);
                            Ext.getCmp('customfieldreadonly').setValue(false);
                		} else {
                			Ext.getCmp('customfieldreadonly').setDisabled(false);                		
                		}
                	}}
            }), new Ext.form.Checkbox({
                id: 'customfieldreadonly',
                fieldLabel: '<span style="cursor:pointer; border-bottom: 1px solid rgb(223, 223, 223);" qtip="This field is read only for customers. Staff may still edit.">'+lang('Read only')+'</span>',
                labelStyle: 'width:124px;',
                name: 'customfieldreadonly'
            }), new Ext.form.Checkbox({
                id: 'customfieldsignup',
                fieldLabel: lang('Include in Signup'),
                labelStyle: 'width:124px;',
                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: [{
            id: "cffieldset1",
            xtype:'fieldset',
            checkboxToggle:false,
            title: 'Field Information',
            hidden:true,
            autoHeight:true,
            defaultType: 'textfield',
            items: fieldItems
        },{
            id: "cffieldset2",
            xtype:'fieldset',
            checkboxToggle:false,
            title: 'Extra Information',
            hidden:true,
            autoHeight:true,
            //defaultType: 'textfield',
            items: extraItems
        }],

        buttons: [{
            id: 'btnSave',
            text: lang('Save'),
            handler  : function() {
                SaveCustomField(); 
            }
        },{
            id: 'customfielddelete',
            text: lang('Delete'),
            disabled: true,
            handler  : function() {
                DeleteCustomField(selectedCustomField); 
            }
        }]
    }) ;
    
    fieldForm.render('customfieldform');
    
    // Hack to hide a form field until needed
    Ext.getCmp('customfieldoptions').setDisabled(true);
    document.getElementById('customfieldoptions').value = '';
    document.getElementById('customfieldoptions').parentNode.parentNode.style.display = 'none';
        
  	if ($('#profiledescription').length > 0) {
  		$('#x-form-el-customfieldcustomerprofile').parent().children("label").css("width","166px");
  		$('#x-form-el-customfieldadminprofile').parent().children("label").css("width","166px");
        $('#x-form-el-customfieldreadonly').parent().show();
  	} else {
        $('#x-form-el-customfieldreadonly').parent().hide();
    }
});

function DeleteCustomField(id)
{
    if (id == 'src' || id == '-1') return;

    Ext.Ajax.request({
       url: "index.php?fuse=admin&action=DeleteCustomField",
       success: function(xhr) {
            ce.parseAjaxResponse(xhr);
            tree.root.reload();
       },
       params: {
           customfieldid : id,
           type: customFieldType
       }
    });
}

function SaveCustomField()
{
    if (selectedCustomField == '-1') return;
    // trick to ensure that all fields get populated
    disableOrEnableFields(1);
    Ext.Ajax.request({
       url: "index.php?fuse=admin&action=SaveCustomField&"+fieldForm.getForm().getValues(true),
       success: function(xhr) {
            ce.parseAjaxResponse(xhr);
            tree.root.reload();
       },
       params: {
           customfieldid : selectedCustomField,
           type: customFieldType,
           customfieldtypevalue: fieldForm.getForm().findField('customfieldtype').getValue()
       }
    });
}

function SelectCustomField(id)
{
    if (id == 'src') return;
    selectedCustomField = id;
    // load the form with custom field details
    fieldForm.getForm().load({
        method: 'GET',
        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;
    }
    
    Ext.Ajax.request({
       url: "index.php?fuse=admin&action=ReorderCustomFields",
       success: function(xhr) {
            ce.parseAjaxResponse(xhr);
            tree.root.reload();
       },
       params: {
           type: customFieldType,
           fields: nodeIds
       }
    });

}

// 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);
        document.getElementById('customfieldoptions').parentNode.parentNode.style.display = '';
    } else {
        Ext.getCmp('customfieldoptions').setDisabled(true);
        document.getElementById('customfieldoptions').parentNode.parentNode.style.display = 'none';
    }
}