var customFields = new function() {
    var ctrl;
    var customFieldsAdded = [];
    var allFieldsDisabled = true;
    var selectListeners = new Array();
    var clickListeners = new Array();
    var deleteRowListeners = new Array();

    var customFieldsStore = new Ext.data.JsonStore({
        root :  "fields",
        totalProperty:  'count',
        idProperty: 'id',
        remoteSort: true,
        fields: ['id','name','description','fieldtype','vtype','value','width','selectfirstonblank','addrowdeletebtn','addrowdeletefnc','isreadonly','ischangeable','listener','isrequired','ishidden','dropdownoptions'],
        proxy:  new Ext.data.HttpProxy({
            url:  'index.php?fuse=support&action=getTicketCustomFields'
        })
    });

    var returnFieldHTML = function(records,options,success, renderer) {
        for(var iterator = 0; iterator < customFieldsStore.data.length; iterator++){
            customFields.getMarkup(customFieldsStore.getAt(iterator).data, renderer);
        }

        if (customFieldsStore.data.length > 0) {
            //check to see if all fields are disabled... if so remove update btn
            if (customFields.getAllFieldsDisabled()){
                $('#ticketCustomFieldsSubmit').hide();
            } else {
                $('#ticketCustomFieldsSubmit').show();
            }

            //lets remove the last |
            $('.ticket-meta-data-box div.customfield:last span').remove();
        }

    };

    var add = function(renderer, control, data, idLabel,metaValue) {
        if (Object.prototype.toString.apply(control) == '[object Array]') {
            $.merge(customFieldsAdded, control);
        } else {
            customFieldsAdded.push(control);
        }

        if ((data != undefined) && ($('#toggleCustomFields').length))  {
            addToMetaData(data,metaValue)
        }

        renderer(control, data, idLabel);
    };

    //Add meta information about custom fields
    var addToMetaData = function(data, metaValue) {
        if (data.value != "") {
            var html = "<div class='customfield'><strong>"+data.name+"</strong>: "+metaValue+" <span style='color:#dfdfdf'>|</span></div>";
            $('#ticketdetails-customfields-min .grid-meta').append(html);
            $('#toggleCustomFields').show();
            $('#ticketdetails-customfields-min').show();
            $('.ticket-header-nocustomfields').removeClass('ticket-header-nocustomfields');
        }
    }

    return {
        submitButtonHandler: function(ticketid, useAlert) {
            for (var i = 0; i < customFieldsAdded.length; i++) {
                if (!customFieldsAdded[i].isValid()) {
                    if (useAlert) {
                        Ext.Msg.alert('Failure', lang('Custom fields may not be submitted with invalid values'));
                    } else {
                        alert(lang('Custom fields may not be submitted with invalid values'));
                    }
                    return false;
                }
            }

            Ext.Ajax.request({
                url: 'index.php?fuse=support&action=SaveCustomFields',
                form: 'ticketCustomFieldsForm',
                params: {
                    ticketId: ticketid
                },
                success:function(t) {
                    $('.ticket-meta-data-box div.customfield').remove();
                    $('#ticketCustomFieldsFormFields div').remove();
                    $('#toggleCustomFields').trigger('click');
                    customFields.load(0, ticketid, function(control, data) {
                        customFields.defaultRenderer(control, data, 'customField_', 'ticketCustomFieldsForm', $('#ticketCustomFieldsFormFields'));
                    });
                    ce.parseAjaxResponse(t);
                }
            });
            return false;
        },

        createSubmitButton: function(ticketid) {
            return new Ext.Button({
                text:     lang('Save Fields'),
                renderTo: 'ticketCustomFieldsSubmit',
                type:     'submit',
                width:    100,
                handler:  function() {
                    customFields.submitButtonHandler(ticketid);
                }
            });
        },

        load: function(ticketType, ticketId, renderer) {
            customFieldsStore.load({
                params: {
                    ticketType: ticketType,
                    ticketId: ticketId
                },
                callback: function(records,options,success) {
                    returnFieldHTML(records,options,success, renderer);
                }
            });
        },

        defaultRenderer: function(control, data, idLabel, formId, fieldsEl) {
            var label;

            if (Object.prototype.toString.apply(control) !== '[object Array]' && control.getXType() == 'hidden') {
                control.render(formId);
            } else {
                data.ishidden = typeof data.ishidden != 'undefinied' && data.ishidden == 1;

                if (data.fieldtype == 49) {
                     fieldsEl.append(String.format('<div id="fieldblock_{1}" '+(data.ishidden? "style='display:none;'" : '')+' class="fieldblock"><dt><dd style="padding-left:0px !important;"><div id="{0}_{1}"></div></dd></dt></div>',
                        idLabel,
                        data.id));
                    control.render("btn_" + data.id);
                } else if (data.fieldtype == 50) {
                     fieldsEl.append(String.format(
                        '<div id="fieldblock_{1}" '+ (data.ishidden? "style='display:none;'" : '') +' class="fieldblock"><dt><dd style="padding-left:0px !important;"><div style="float:left;" id="dnshostname_{1}"></div><div style="float:left;padding-left:5px;" id="dnshosttype_{1}"></div><div style="float:left;padding-left:5px;" id="dnshostaddress_{1}"></div><div style="float:left;padding-left:5px;" id="{0}_{1}"></div></dd></dt></div>',
                        idLabel,
                        data.id
                    ));
                    control[0].render('dnshostname_' + data.id);
                    control[1].render('dnshosttype_' + data.id);
                    control[2].render('dnshostaddress_' + data.id);
                } else {
                    if (data && data.description) {
                        label = '<span style="cursor:pointer; border-bottom: 1px solid rgb(223, 223, 223);" qtip="' +
                            data.description + '">' + data.name + '</span>';
                    } else {
                        label = data.name;
                    }
                    fieldsEl.append(String.format(
                        '<div id="fieldblock_{2}" ' + (data.ishidden? "style='display:none;'" : '') + ' class="fieldblock"><dt><label>{0}</label></dt><dd class="ddelement" style="width:290px;"><div style="float:left;" id="{1}_{2}"></div><div style="float:left;padding-left:5px;" id="deleterowbtn_{2}"></div></dd></div>',
                        label,
                        idLabel,
                        data.id
                    ));
                    control.render(idLabel + "_" + data.id);
                }
            }
        },

        getMarkup: function(currentFieldData, renderer) {
            var width;

            var isComboType = false
            var currentFieldValue = currentFieldData.value;
            var allowBlankValue = true;
            var isDisabled = true;
            var selectFirstOnBlank = true;

            ctrl = null;

            if(currentFieldData.isrequired == 1){
                allowBlankValue = false;
            }

            if(currentFieldData.ischangeable ==1){
                isDisabled = false;
                allFieldsDisabled = false;
            }

            if (typeof(currentFieldData.selectfirstonblank) != "undefined"){
                if (!currentFieldData.selectfirstonblank) {
                    selectFirstOnBlank = false;
                }
            }

            var createHiddenTypeField = false;
            var controlid = currentFieldData.id;
            if (isInteger(currentFieldData.id)) {
                controlid = 'CT_' + currentFieldData.id;
                createHiddenTypeField = true;
            }
            var metaValue = '';
            switch(currentFieldData.fieldtype){
                case '52':
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    ctrl = new Ext.form.TextField({
                        id:               controlid,
                        name:             controlid,
                        fieldLabel:       currentFieldData.name,
                        labelStyle:       'font-weight:bold;font-size:11px;',
                        value:            currentFieldValue
                    });
                    currentFieldData.ishidden = true;
                    add(renderer, ctrl, currentFieldData, 'deleterowbtn',metaValue);
                    break;
                case '0':   // typeTEXTFIELD
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    ctrl = new Ext.form.TextField({
                        id:               controlid,
                        name:             controlid,
                        fieldLabel:       currentFieldData.name,
                        labelStyle:       'font-weight:bold;font-size:11px;',
                        width:            width,
                        disabled:         isDisabled,
                        border:           false,
                        value:            currentFieldValue,
                        allowBlank:       allowBlankValue,
                        validationEvent: false,
                        blankText:        lang("This field is required")
                    });
                    add(renderer, ctrl, currentFieldData, 'textfield',currentFieldValue);
                    break;
                case '54':   // typeNUMBER
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    ctrl = new Ext.form.NumberField({
                        id:               controlid,
                        name:             controlid,
                        fieldLabel:       currentFieldData.name,
                        labelStyle:       'font-weight:bold;font-size:11px;',
                        width:            width,
                        disabled:         isDisabled,
                        border:           false,
                        value:            currentFieldValue,
                        allowBlank:       allowBlankValue,
                        validationEvent: false,
                        blankText:        lang("This field is required")
                    });
                    add(renderer, ctrl, currentFieldData, 'textfield',currentFieldValue);
                    break;
                case '10': //typeTextArea
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    ctrl = new Ext.form.TextArea({
                        id:     controlid,
                        name:   controlid,
                        fieldLabel:       currentFieldData.name,
                        labelStyle:       'font-weight:bold;font-size:11px;',
                        width:            width,
                        disabled:         isDisabled,
                        border:           false,
                        validationEvent:  false,
                        allowBlank:       allowBlankValue,
                        blankText:        lang("This field is required"),
                        value:            currentFieldValue
                    });
                    add(renderer, ctrl, currentFieldData, 'textarea',currentFieldValue);
                    break;
                case '1':   // typeYESNO
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    isComboType = true;
                    storeObject = [[0,lang('No')],[1,lang('Yes')]];
                    ctrl = new Ext.form.ComboBox({
                            id:               'ctrl' + controlid,
                            name:             controlid,
                            fieldLabel:       currentFieldData.name,
                            labelStyle:       'font-weight:bold;font-size:11px;',
                            hiddenName:       controlid,
                            typeAhead:        true,
                            triggerAction:    'all',
                            lazyRender:       true,
                            mode:             'local',
                            width:            width,
                            disabled:         isDisabled,
                            store:            storeObject,
                            allowBlank:       false,
                            blankText:        lang("This field is required"),
                            forceSelection:   true,
                            editable:         false,
                            selectOnFocus:    true,
                            value:            currentFieldValue
                        });

                        if ( (currentFieldValue=="") || (currentFieldValue==null)) {
                            Ext.getCmp('ctrl' + controlid).setValue(Ext.getCmp('ctrl' + controlid).getStore().getAt(0).data.field1);
                        }
                        metaValue = (currentFieldValue == 0) ? lang("No") : lang("Yes");
                        add(renderer, ctrl, currentFieldData, 'yesno',metaValue);
                    break;
                case '6':   // typeCOUNTRY
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    isComboType = true;
                    storeObject = currentFieldData.dropdownoptions;
                    ctrl = new Ext.form.ComboBox({
                            id:               controlid,
                            name:             controlid,
                            fieldLabel:       currentFieldData.name,
                            labelStyle:       'font-weight:bold;font-size:11px;',
                            typeAhead:        true,
                            triggerAction:    'all',
                            lazyRender:       true,
                            mode:             'local',
                            disabled:         isDisabled,
                            width:            width,
                            store:            storeObject,
                            allowBlank:       false,
                            blankText:        lang("This field is required"),
                            forceSelection:   true,
                            editable:         false,
                            selectOnFocus:    true,
                            value:            currentFieldValue
                        });
                        if ( (currentFieldValue=="") || (currentFieldValue==null)) {
                            Ext.getCmp(controlid).setValue(Ext.getCmp(controlid).getStore().getAt(0).data.field1);
                        }
                        add(renderer, ctrl, currentFieldData, 'country',metaValue);
                    break;
                case '30': //product status
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    isComboType = true;
                    storeObject = currentFieldData.dropdownoptions;
                    ctrl = new Ext.form.ComboBox({
                            id:               'ctrl' + controlid,
                            name:             controlid,
                            hiddenName:       controlid,
                            fieldLabel:       currentFieldData.name,
                            labelStyle:       'font-weight:bold;font-size:11px;',
                            typeAhead:        true,
                            triggerAction:    'all',
                            lazyRender:       true,
                            mode:             'local',
                            width:            width,
                            store:            storeObject,
                            allowBlank:       false,
                            blankText:        lang("This field is required"),
                            forceSelection:   true,
                            editable:         false,
                            selectOnFocus:    true,
                            value:            currentFieldValue
                        });
                        if (!packageemanager.productData.Permissions.changestatus) {
                           Ext.getCmp('ctrl' + controlid).setDisabled(true);
                        }
                        add(renderer, ctrl, currentFieldData, 'dropdown',metaValue);
                    break;
                case '9': //dropdown
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    isComboType = true;
                    if (currentFieldData.vtype == ""){
                        currentFieldData.vtype = null;
                    }
                    storeObject = currentFieldData.dropdownoptions;
                    ctrl = new Ext.form.ComboBox({
                        id:               "ctrl"+controlid,
                        name:             controlid,
                        fieldLabel:       currentFieldData.name,
                        labelStyle:       'font-weight:bold;font-size:11px;',
                        hiddenName:       controlid,
                        typeAhead:        true,
                        triggerAction:    'all',
                        lazyRender:       true,
                        mode:             'local',
                        disabled:         isDisabled,
                        width:            width,
                        tpl: new Ext.XTemplate(
                            '<tpl for="."><div class="x-combo-list-item" qtip="{field2}">',
                            '{field2}',
                            '</div></tpl>'
                            ),
                        store:            storeObject,
                        allowBlank:       false,
                        blankText:        lang("This field is required"),
                        forceSelection:   true,
                        editable:         false,
                        vtype:            currentFieldData.vtype,
                        selectOnFocus:    true,
                        value:            currentFieldValue,
                        isreadonly:       currentFieldData.isreadonly
                    });

                    //add listeners to unique dropdowns
                    if(currentFieldData.id == "group") {
                        Ext.getCmp("ctrl"+controlid).setDisabled(true);
                    }


                    //if we don't pass back a value do not set initial value
                    if ( selectFirstOnBlank && ( (currentFieldValue=="") || (currentFieldValue==null) )) {
                        Ext.getCmp("ctrl"+controlid).setValue(Ext.getCmp("ctrl"+controlid).getStore().getAt(0).data.field1);
                    }

                    v = ctrl.getValue();
                    record = ctrl.findRecord(ctrl.valueField || ctrl.displayField, v);
                    if (typeof(record) != "undefined") metaValue = record.data.field2;
                    else metaValue = currentFieldValue;

                    add(renderer, ctrl, currentFieldData, 'dropdown',metaValue);
                    break;
                 case '15':  //  typeDATE
                    if (currentFieldValue != '' && currentFieldValue != '00/00/0000') {
                        //currentFieldValue = (new Date(Date.parse(currentFieldValue))).dateFormat(gDateFormat);
                        currentFieldValue = currentFieldValue;
                    }else {
                        currentFieldValue = '';
                    }
                    ctrl = new Ext.form.DateField({
                            id:               controlid,
                            name:             controlid,
                            fieldLabel:       currentFieldData.name,
                            labelStyle:       'font-weight:bold;font-size:11px;',
                            height:           "5px",
                            selectOnFocus:    true,
                            width:            200,
                            format:           gDateFormat,
                            disabled:         isDisabled,
                            value:            currentFieldValue,
                            allowBlank:       false,
                            validationEvent: false,
                            blankText:        lang("This field is required")
                    });
                    if ( (currentFieldValue=="") || (currentFieldValue==null)) {
                        Ext.getCmp(controlid).setValue(new Date());
                    }
                    add(renderer, ctrl, currentFieldData, 'date',currentFieldValue);
                    break;
                 case '53':
                    width = (currentFieldData.width) ? currentFieldData.width : 20;
                    ctrl = new Ext.form.Checkbox({
                        id:               controlid,
                        name:             controlid,
                        width:            width,
                        disabled:         isDisabled,
                        border:           false,
                        value:            currentFieldValue,
                        allowBlank:       allowBlankValue,
                        validationEvent: false,
                        blankText:        lang("This field is required")
                    });
                    add(renderer, ctrl, currentFieldData ,'textfield',currentFieldValue);

                    break;
                 case '49':
                     //default to length of 380 as most fields are that length
                     width = (currentFieldData.width) ? currentFieldData.width : 380;
                     ctrl = new Ext.Button({
                         id: controlid,
                         name: controlid,
                         width: width,
                         text: currentFieldValue
                     });
                     add(renderer, ctrl, currentFieldData, 'btn',metaValue);
                     break;
                 case '50':
                     storeObject = [['A','A'],['MXE','MXE'],['MX','MX'],['CNAME','CNAME'],['URL','URL'],['FRAME','FRMAE'],['TXT','TXT']];
                     ctrl = [
                         new Ext.form.TextField({
                            id:               "hostname_"+controlid,
                            name:             "hostname_"+controlid,
                            width:            50,
                            disabled:         isDisabled,
                            border:           false,
                            value:            currentFieldValue.hostname,
                            allowBlank:       false,
                            validationEvent: false,
                            blankText:        lang("This field is required")
                        }),
                        new Ext.form.ComboBox({
                            id:               "hosttype_"+controlid,
                            name:             "hosttype_"+controlid,
                            typeAhead:        true,
                            triggerAction:    'all',
                            lazyRender:       true,
                            mode:             'local',
                            width:            70,
                            disabled:         isDisabled,
                            store:            storeObject,
                            allowBlank:       false,
                            blankText:        lang("This field is required"),
                            forceSelection:   true,
                            editable:         false,
                            selectOnFocus:    true,
                            value:            currentFieldValue.hosttype
                        }),
                        new Ext.form.TextField({
                            id:               "hostaddress_"+controlid,
                            name:             "hostaddress_"+controlid,
                            width:            220,
                            disabled:         isDisabled,
                            border:           false,
                            value:            currentFieldValue.address,
                            allowBlank:       false,
                            validationEvent: false,
                            blankText:        lang("This field is required")
                        })
                    ];
                    add(renderer, ctrl, currentFieldData, 'deleterowbtn',metaValue);
                    break;
            }

            //add hidden for type if we have a custom field
            if (createHiddenTypeField) {
                var hiddenCtrl = new Ext.form.Hidden ({
                    id: 'CTT_' + currentFieldData.id,
                    name : 'CTT_' + currentFieldData.id,
                    cls: 'hiddenCustomField',
                    value: currentFieldData.fieldtype
                });

                add(renderer, hiddenCtrl);
            }

            //dynmamic listeners passed back by store
            if (currentFieldData.listener.onselect) {
                selectListeners[ctrl.getId()] = currentFieldData.listener.onselect;
                if (isComboType){
                    ctrl.on("beforeselect", function (combo,record,index){
                        if (combo.getValue() == record.data.field1) {
                            combo.collapse();
                            return false;
                        }else{
                            return true;
                        }
                    },ctrl);
                }
                ctrl.on("select", function (){
                    eval(selectListeners[this.id]+ '()')
                },ctrl);
            }

            //dynamic listener for click
            if(currentFieldData.listener.onclick) {
                clickListeners[ctrl.getId()] = currentFieldData.listener.onclick;
                ctrl.on("click", function () {
                    eval(clickListeners[this.id]+ '()')
                },ctrl);
            }

            //add row delete button expects div to exist
            if(currentFieldData.addrowdeletebtn) {
                deleteRowListeners[controlid+"_delete"] = currentFieldData.addrowdeletefnc;
                new Ext.Button({
                     id: controlid+"_delete",
                     name: controlid+"_delete",
                     renderTo : 'deleterowbtn_' + currentFieldData.id,
                     width: 20,
                     cls: 'x-box-text-small',
                     text: 'X',
                     handler: function() {
                         eval(deleteRowListeners[this.id]+ '(this)')
                     }
                 });
            }
        },

        validateCustomFields: function(message) {
            var valid = true;
            $.each(customFieldsAdded, function() {
                if (!this.validate() && !this.initialConfig.isreadonly) {
                    valid = false;
                    if (message == undefined) {
                        return false;
                    }
                    if (Object.prototype.toString.apply(message) !== '[object Array]') {
                        if (message != '') {
                            message += '<br />';
                        }
                        message += this.initialConfig.fieldLabel
                    } else {
                        message.push(lang('Please enter a valid value for %', this.initialConfig.fieldLabel));
                    }
                }
            });
            if (message != undefined) {
                return message;
            }
            return valid;
        },

        getAllFieldsDisabled: function() {
            return allFieldsDisabled;
        },

        getCustomFieldsAdded: function() {
            return customFieldsAdded;
        },

        resetCustomFields: function() {
            customFieldsAdded = [];
        }
    };
}();

$(document).ready(function(){
    $('#toggleCustomFields').bind('click',function(){
        $('.ticket-customfields').toggle();
        $('#ticketdetails-customfields-min').toggle();
    });

});
