//namespace for packagemanager for userpackages
var packageemanager = {};
packageemanager.package_id = 0;
packageemanager.arrayOfLazyLoadingPanels = ["hosting","domaininfo","hostrecords","nameservers"]; //any panel setting type that requires lazy loading needs to be in this list
packageemanager.activeTab = "groupinfo";

Ext.onReady(function(){

    /**
    * Show settings for the product by a given setting type like billing, hosting, general
    */
    packageemanager.showManageSettingByType = function(typeid,options) {

        // Hide the panel error box.
        if(document.getElementById('panelErrorBox')) {
            document.getElementById('panelErrorBox').style.visibility = 'hidden';
            document.getElementById('panelErrorBox').style.display = 'none';
        }

        if (typeof(typeid) == "object"){
            //this means it was returned from store load callback so get id from options
            typeid = options.params.typeid
        }
        document.getElementById("selectedproduct-view").innerHTML = "";
        $(".vtab").each(function (index, domEle) {
            domEle.className = "vtab";
        });
        packageemanager.activeTab = typeid;
        document.getElementById('settingtype_'+typeid).className = "vtab active";
        
        packageemanager.product_store_general.load({
            params:{
                settingtype:typeid,
                packageId:packageemanager.package_id,
                start:0,
                //limit:50
                limit:0
            },
            callback:packageemanager.returnFieldHTML
        });
        packageemanager.viewingSettingPanel = typeid;
        
        //call function to determine what to do with plugin variables
        if(packageemanager.productData.hasplugin){
            packageemanager.updateAvailablePluginActions();
        }
        
    }

    // Start a reader for populating product list
    packageemanager.entries_store_reader = new Ext.data.JsonReader({
            totalProperty: "totalcount",
            root: "results",
            id: "id"
        },
        Ext.data.Record.create(['id','producttype','Permissions','productgroupname','recurringcharges','productid','name','group','desc','desc_details','renewal','signup','status','status_class', 'status_id'])
    );
        
    packageemanager.entries_store = new Ext.data.GroupingStore({
        id:       "entries_store",
        url:      'index.php?fuse=clients&action=adminGetUserPackages&filteroncustomer=1',
        reader:   packageemanager.entries_store_reader,
        sortInfo: {
            field: 'renewal', 
            direction:  "asc"
        },
        listeners : {
            load : function (Store, records,options) {
                var productlistcombo_store = packageemanager.productlistcombo.getStore();
                var canDelete = false;
                productlistcombo_store.removeAll();
                var MyRecordType = Ext.data.Record.create(['id', 'name','desc','productid']);
                var myrec = new MyRecordType({
                    "productid":0, 
                    "name":lang("All Products"),
                    "desc":lang("Select to view all products")
                });
                productlistcombo_store.add(myrec);
                for(var iterator = 0; iterator < Store.data.length; iterator++){
                    var currentFieldData = Store.getAt(iterator).data;
                    myrec = new MyRecordType({
                        "productid":currentFieldData.productid, 
                        "name":currentFieldData.name,
                        "desc":currentFieldData.desc
                    });
                    productlistcombo_store.add(myrec);

                    //we are returning permissions per row but some are global so lets just get first row permissions to set for entire group
                    //we can look at this later once we think we might switch permissions per specific item or product type
                    canDelete = (currentFieldData.Permissions.candelete) ? true : canDelete;
                }

                packageemanager.productlistcombo.setValue(packageemanager.package_id);
                /* TODO4.2
				if (canDelete) {
                    Ext.getCmp('deleteproducts').setVisible(true);
                }*/

            }
        }
    });

    //combo list of products
    packageemanager.productlistcombo = new Ext.form.ComboBox({
        store : new Ext.data.ArrayStore({idIndex: 0,fields: ['productid','name','desc']}),
        applyTo: 'productlist',
        editable:false,
        triggerAction: 'all',
        value: lang('All Products'),
        lazyRender:false,
        mode:'local',
        valueField:'productid',
        width: 320,
        listWidth: 400,
        tpl: new Ext.XTemplate(
            '<tpl for="."><div class="x-combo-list-item" ext:qtip="{desc}">',
            '{name}',
            '</div></tpl>'
            ),
        displayField:'name',
        listeners : {
            select : function(combo,record,index) {
                if (record.data.productid == 0 ) {
                    shiftProductViewToAll();
                } else {
                    packageemanager.shiftProductViewForId(record.data.productid);
                }
            }
        }
    });
    packageemanager.productlistcombo.wrap.addClass("x-form-field-float-left");

    filterstore = new Ext.data.JsonStore({
        id:             "filterstore",
        root:           'options',
        idProperty:     'value',
        remoteSort:     true,
        fields:         ['id','name','type'],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=clients&action=Admin_GetFilters'
        })
    });
    filterstore.load();

    //create combo for group by filter
    new Ext.form.ComboBox({
       triggerAction: 'all',
       lazyRender:true,
       editable:false,
       value: '0',
       width: 120,
       store: [[0,lang('None')],[1,lang('Product Bundle')],[2,lang('Type')]],
       mode:  'local',
       applyTo: 'groupbyfilter',
       listeners: {
            'select' : function (cb,record) {
                if (cb.getValue() == 0) {
                    packageemanager.entries_store.groupBy("");
                } else if (cb.getValue() == 1) {
                    packageemanager.entries_store.groupBy("group");
                } else if (cb.getValue() == 2) {
                    packageemanager.entries_store.groupBy("productgroupname");
                }
            }
        }
    });

    // Create the dropdown of Registrar plugins
    new Ext.form.ComboBox({
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value:lang('All'),
        width: 120,
        store:filterstore,
        displayField:'name',
        hiddenName: 'plugin',
        valueField:'id',
        mode:'local',
        beforeBlur : Ext.emptyFn,
        applyTo: 'productfilter',
        listeners:{
            'select': function(cb,record){
                domainsFilterGrid(record.data.id);
            }
        }
    });

    function domainsFilterGrid(type) {
        packageemanager.entries_store.setBaseParam('filter', type);
        packageemanager.entries_store.setBaseParam('sort', 'domainname');
        packageemanager.entries_store.setBaseParam('dir', 'ASC');
        packageemanager.entries_store.load({params:{start:0}});
    }

    /**
     * Lets get the status buttons back dynamically
     */
    function toggleButtons(count){

        count = sm.getCount();
        if(count == 0) {
            // Hide everything
            Ext.getCmp('sendbuttons').setDisabled(true);
            //TODO 4.2 Ext.getCmp('deleteproducts').setDisabled(true);
        } else {

            // Show Buttons
            Ext.getCmp('sendbuttons').setDisabled(false);
            //TODO 4.2 Ext.getCmp('deleteproducts').setDisabled(false);

        }
    }

    if(document.getElementById('gridaddproductbtn') != null){
        new Ext.Button({
            id:"gridaddproductbtn",
            renderTo:"gridaddproductbtn",
            text: lang('Add Product'),
            disabled : (!canaddeditpackages) ? true : false,
            handler: function() {
                 addPackage($('#gridaddproductbtn').offset().left,($('#gridaddproductbtn').offset().top+5));
            }
        });
    }

    function addPackage(x,y) {
        //show window to add package
        packageemanager.addPackageWindow = new Ext.Window({
            id:           "winAddPackage",
            labelAlign:   'right',
            layout:       'form',
            width:        350,
            modal:        true,
            x: x,
            y: y,
            bodyStyle:    'padding:8px 15px 8px',
            autoHeight:   true,
            defaultType:  'textfield',
            closeAction:  'close',
            shadow:       false,
            title:        lang("Add Package:"),
            plain:        true,
            closable:     true,
            buttonAlign:  'right',
            items:        [
            new Ext.form.ComboBox({
                id:         'newProductGroup',
                name:       'newProductGroup',
                fieldLabel: lang("Product Group"),
                triggerAction:    'all',
                disabled: true,
                lazyRender:       true,
                mode:             'local',
                border:     false,
                forceSelection:   true,
                editable:         false,
                valueField: 'myId',
                displayField: 'displayText',
                selectOnFocus:    true,
                store : new Ext.data.ArrayStore({
                    idIndex: 0,
                    fields: [
                    'myId',
                    'displayText'
                    ],
                    data: [['0', 'item1']]
                }),
                anchor:     '100%',
                allowBlank: false,
                listeners : {
                    select : function (combo, record, index) {
                        productgroupid = Ext.getCmp('newProductGroup').getValue();
                        //disable the button
                        Ext.getCmp('btnAddPackage').setDisabled(true);
                        // I need to update the newPackage List
                        cb = Ext.getCmp('newPackage');
                        cb.setDisabled(true);
                        Ext.getCmp('newDomainName').setDisabled(true);
                        Ext.getCmp('isTransfer').setDisabled(true);
                        Ext.Ajax.request({
                            url: 'index.php?fuse=admin&action=getGroupProducts',
                            success: function(xhr) {
                                var json = ce.parseAjaxResponse(xhr);
                                cb = Ext.getCmp('newPackage');
                                cb.clearValue();
                                cb.getStore().loadData(json.results);
                                //show selection is of type domain
                                if (json.productGroupType == 3) {
                                    Ext.getCmp('newDomainName').setVisible(true);
                                    Ext.getCmp('newDomainName').setDisabled(false);
                                    Ext.getCmp('isTransfer').setVisible(true);
                                    Ext.getCmp('isTransfer').setDisabled(false);
                                } else {
                                    Ext.getCmp('newDomainName').setVisible(false);
                                    Ext.getCmp('newDomainName').setDisabled(true);
                                    Ext.getCmp('isTransfer').setVisible(false);
                                    Ext.getCmp('isTransfer').setDisabled(true);
                                }
                                cb.setValue(json.results[0][0]);
                                cb.setDisabled(false);
                                Ext.getCmp('btnAddPackage').setDisabled(false);
                            },
                            params: {
                                productgroup_id: productgroupid
                            }
                        });
                    }
                }
            }),
            new Ext.form.ComboBox({
                id:         'newPackage',
                name:       'newPackage',
                fieldLabel: lang("Product"),
                lazyRender:       true,
                mode:             'local',
                triggerAction:    'all',
                disabled: true,
                forceSelection:   true,
                editable:         false,
                valueField: 'myId',
                displayField: 'displayText',
                selectOnFocus:    true,
                store : new Ext.data.ArrayStore({
                    idIndex: 0,
                    fields: [
                    'myId',
                    'displayText'
                    ],
                    data: [[0, 'item1']]
                }),
                border:     false,
                anchor:     '100%',
                allowBlank: false
            }),{
                id: 'newDomainName',
                name: 'newDomainName',
                hidden: true,
                allowBlank : false,
                blankText:        lang("This field is required"),
                fieldLabel: lang("Domain Name"),
                width: 200,
                onHide: function(){
                    this.getEl().up('.x-form-item').setDisplayed(false);
                },
                onShow: function(){
                    this.getEl().up('.x-form-item').setDisplayed(true);
                }
            },
            new Ext.form.Checkbox({
                id:               'isTransfer',
                name:             'isTransfer',
                hidden: true,
                allowBlank : false,
                fieldLabel: lang("Mark as Transfer"),
                width: 200,
                onHide: function(){
                    this.getEl().up('.x-form-item').setDisplayed(false);
                },
                onShow: function(){
                    this.getEl().up('.x-form-item').setDisplayed(true);
                }
            })
        
            ],
            buttons:      [
            {
                id:       'btnAddPackage',
                text:     lang("Add"),
                disabled: false,
                hidden:   false,
                handler:  function(){
                          
                    passdomain = "";
                    //Start domain related extra steps 
                    //validate form
                    if (Ext.getCmp('newDomainName').isVisible() ) {
                        if (!Ext.getCmp('newDomainName').isValid()) {
                            Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                            return;
                        }
                        passdomain = "&domainname="+Ext.getCmp('newDomainName').getValue();
                        passdomain = passdomain + "&isTransfer=" + Ext.getCmp('isTransfer').getValue();
                    }
                    //End domain related extra steps 
                        
                    Ext.Ajax.request({
                        url: 'index.php?fuse=clients&action=SaveProductForCustomer'+passdomain,
                        success: function(xhr) {
                            json = ce.parseAjaxResponse(xhr);
                            if(!json.error) {
                                packageemanager.addPackageWindow.close();
                                window.location.href = "index.php?fuse=clients&view=Admin_Profile_Products&packageid="+json.newid;
                            //show the newly added product
                            }
                        },
                        params: {
                            productgroupid:Ext.getCmp('newProductGroup').getValue(),
                            productid:Ext.getCmp('newPackage').getValue()
                        }
                    });
                }
            }
            ]
        });

        //populate the comboboxes
        Ext.Ajax.request({
            url: 'index.php?fuse=admin&action=getGroups',
            success: function(xhr) {
                var json = ce.parseAjaxResponse(xhr);
                cb = Ext.getCmp('newProductGroup');
                cb.getStore().loadData(json.results);
                cb.setValue(json.results[0][0]);
                cb.setDisabled(false);
                cb.fireEvent('select');
            }
        });
        packageemanager.addPackageWindow.show();
    }

    packageemanager.deleteGridProduct = function(deleteFromGrid){
        var packageids = packageemanager.package_id;
        if (deleteFromGrid) {
            //get package_ids from selected items in grid
            packageids = packageemanager.getProductItems()
        }
        packageemanager.loadingMask.show();
        Ext.Ajax.request({
            url: 'index.php?fuse=clients&action=adminDeletePackages',
            success: function(xhr) {
                var json = ce.parseAjaxResponse(xhr);
                if (!json.error) {
                    window.location.href = "index.php?fuse=clients&view=Admin_Profile_Products";
                }else {
                   packageemanager.loadingMask.hide();
                }
            },
            params: {
                domainid: packageids,
                performonserver: $('#performonserver:checked').val()
            }
        });
    }

    packageemanager.TogglePackageStatusPackageId = 0;
    packageemanager.TogglePackageStatus = function(packageid, currentStatus) {
        packageemanager.TogglePackageStatusPackageId = packageid;
        $('#productstatudropdown').show();
        var x = $('#linkforproductstatus_'+packageid).offset().left-8;
        var y = $('#linkforproductstatus_'+packageid).offset().top -2;
        $('.productstatus').show();
        $('#linkforproductstatus_'+packageid).hide();

        if(!packageemanager.productstatudropdown) {
            packageemanager.productstatudropdown = new Ext.form.ComboBox({
                triggerAction: 'all',
                lazyRender:true,
                editable:false,
                width: 60,
                store : new Ext.data.ArrayStore({idIndex: 0,fields: ['id','name']}),
                displayField:'name',
                valueField:'id',
                mode:'local',
                applyTo: 'productstatudropdown',
                listeners:{
                    'select': function(cb, record){
                        recurringgrid.disable();
                        Ext.Ajax.request({
                            url : 'index.php?fuse=clients&action=adminUpdateUserPackage',
                            success: function(xhr) {
                                recurringgrid.enable();
                                packageemanager.productstatudropdown.setVisible(false);
                                packageemanager.entries_store.load();                        
                                json = ce.parseAjaxResponse(xhr);

                            },
                            params : {userPackageId:packageemanager.TogglePackageStatusPackageId,settingtype:'groupinfo',productstatus:cb.getValue()}
                        });
                    }
                }
            });
        } else {
            packageemanager.productstatudropdown.setVisible(true);
        }
        
        var store = packageemanager.productstatudropdown.getStore();
        store.removeAll();
        packageemanager.productstatudropdown.setPagePosition(x,y);
        Ext.Ajax.request({
            url: 'index.php?fuse=clients&action=getProductStatuses',
            params:   {packageId: packageid},
            success: function(xhr) {
                var json = ce.parseAjaxResponse(xhr);
                //packageemanager.productstatudropdown
                var store = packageemanager.productstatudropdown.getStore();
                var MyRecordType = Ext.data.Record.create(['id', 'name']);
                dropdownoptions = json.statuses[0].dropdownoptions;
                for (var x=0; x< dropdownoptions.length; x++) {
                    myrec = new MyRecordType({
                        "id":dropdownoptions[x][0], 
                        "name":dropdownoptions[x][1]
                    });
                    store.add(myrec);
                }
                packageemanager.productstatudropdown.setValue(currentStatus);
            }
        });
        
        return false;
        if(document.getElementById('label_customerstatus').style.display == "none"){
            document.getElementById('label_customerstatus').style.display = "";
            Ext.getCmp('productstatuscombo').setVisible(false);
            //call store load for package status
        }else{
            document.getElementById('label_customerstatus').style.display = "none";
            Ext.getCmp('productstatuscombo').setVisible(true);
            //call store load for package status
        }
    }

    packageemanager.getProductItems = function(){
        var invoiceItems = "";
        rows = sm.getSelections();
        for(x=0;x<rows.length;x++){
            var commavar = ",";
            if(x !=0){
                invoiceItems += commavar;
            }
            invoiceItems += rows[x].data.productid;
        }
        return invoiceItems;
    }
	
    /*
     * Fucntions to load the grid
     */
    var sm = new Ext.grid.CheckboxSelectionModel({
        checkOnly: true,
        listeners:{
            'rowdeselect': function(model, rowIndex, record){
                toggleButtons();
            },
            'rowselect': function(model, rowIndex, record){
                toggleButtons();
            }
        }
    });

    // Define the rendered of the name, to provide a link
    function renderName(value,p,record) {
        
        if (record.data.desc_details == "") { 
            name = '<div><a ext:qtip="'+record.data.desc+'" href="javascript:packageemanager.shiftProductViewForId(' + record.data.productid + ');" id="' + record.data.id + '">' + record.data.name + '</a>';
            name += "<div style='font-size:10px;color:#989898;padding-top:3px;'>&nbsp;</div></div>";
        } else {
            name = '<div style="position:relative; top:-6px;"><a ext:qtip="'+record.data.desc+'" href="javascript:packageemanager.shiftProductViewForId(' + record.data.productid + ');" id="' + record.data.id + '">' + record.data.name + '</a>';
            name += "<div style='font-size:10px;color:#989898;padding-top:3px;'>"+record.data.desc_details+"</div></div>";
        }
        return name;
    }
	
    function renderStatus(value,p,record) {
        p.css = record.data.status_class;
        if (record.data.Permissions.changestatus) {
            html = '<span class="productstatus" id="linkforproductstatus_'+record.data.id+'"><a id="aforproductstatus_'+record.data.id+'" style="border-bottom: 1px dotted red !important;text-decoration: none;" onclick="packageemanager.TogglePackageStatus('+record.data.id+','+record.data.status_id+');">'+record.data.status+'</a></span>';
        } else {
            html = record.data.status;
        }
        return html;
    }

    function renderRenewal(value,p,record) {
        if (record.data.recurringcharges == "----") {
            return "----";
        } else {
            return record.data.renewal;
        }
    }

    // Make the grid
    var recurringgrid = new Ext.grid.GridPanel({
        store:packageemanager.entries_store,
        columns: [
        sm,	            
        {
            header: lang("Description"), 
            sortable: true,
            dataIndex: 'id',
            renderer: renderName
        },
        {
            header: lang("Type"), 
            width: 40,
            hidden: true,
            sortable: true, 
            align:'center', 
            dataIndex: 'productgroupname'
        },
        {
            header: lang("Invoice Date"), 
            width: 27, 
            sortable: true,  
            align:'center',
            renderer: renderRenewal,
            dataIndex: 'renewal'
        },
        {
            header: lang("Invoice Amount"), 
            width: 27, 
            sortable: false,  
            align:'center',
            dataIndex: 'recurringcharges'
        },
        {
            header: lang("Status"), 
            width: 15, 
            sortable: true,  
            align:'center',
            renderer: renderStatus
        },
        {
            header: lang("Product"), 
            width: 20, 
            sortable: true, 
            hidden:true, 
            dataIndex: 'group'
        }
        ],
        view: new Ext.grid.GroupingView({
            scrollOffset:1,
            forceFit:true,
            groupFit:true,
            emptyText: lang("There are no products available"),
            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})' //{text} 
        }),
        frame:false,
        loadMask: true,
        columnLines: true,
        autoHeight:true,
        sm:               sm,
        stripeRows: true,
        collapsible: false,
        buttonAlign:'left',
        iconCls: 'icon-grid',
        id:       'domains-grid',
        el:       'domains-grid',
        buttons:[
            {
                id:         'sendbuttons',
                text:       lang('Send Welcome E-Mail'),
                disabled: true,
                onClick:  function(record){
                    if(!Ext.getCmp('sendbuttons').disabled) {
                        recurringgrid.disable();
                        Ext.Ajax.request({
                            url:      "index.php?fuse=clients&action=sendWelcomeEmail",
                            params:   {packages: packageemanager.getProductItems()},
                            success:  function(xhr){
                                recurringgrid.enable();
                                packageemanager.entries_store.load({params:{start:0}});
                                ce.parseAjaxResponse(xhr);
                            },
                            failure:  function(){recurringgrid.enable();}
                        });
                    }
                }
            }/* TODO4.2
				,{
                id:'deleteproducts',
                text: lang('Delete Products'),
                disabled: true,
                hidden: true,
                onClick:  function(record){
                    if(!Ext.getCmp('deleteproducts').disabled) {
                        packageemanager.promptToDeleteProduct(true);
                    }
                }
            }*/
        ]
    });

    packageemanager.promptToDeleteProduct = function(deleteFromGrid) {
        if (deleteFromGrid) {
        } else {
            deleteFromGrid = false;
        }
        
        Ext.Msg.show({
            title:    "Delete?",
            msg:      "Are you sure you want to delete the selected product(s)?",
            buttons:  Ext.Msg.YESNO,
            disabled: true,
            fn:       function(btn, text){
                if(btn == 'yes'){
                    packageemanager.deleteGridProduct(deleteFromGrid);
                }
            },
            icon:     Ext.MessageBox.QUESTION
        });
    }

    // Load the group products
    domainsFilterGrid('all_all');
    // render grid
    recurringgrid.render();
    
    
    /**
     * Update the plugin drop down actions
     */
    packageemanager.updateAvailablePluginActions = function()
    {
        Ext.Ajax.request({
            url: 'index.php?fuse=clients&action=getAvailablePluginActions',
            success: function(xhr) {
                var json = ce.parseAjaxResponse(xhr);
                //call to populate plugin options from ajax call or initial productData call
                //ensure when we get new product data that we recreate this list
                
                var pluginActionMenu = Ext.getCmp('pluginactiondropdownmenu');
                pluginActionMenu.removeAll();
                var count=0;
                for ( var i in json.pluginActions )
                {
                    if (typeof json.pluginActions[i] != "object") continue;
                    var comboitem = new Ext.menu.Item({
                        itemId: json.pluginActions[i].cmd,
                        text: json.pluginActions[i].label
                    });
                    comboitem.addListener("click", function(menuItem, e ){
                        
                        //call special methods for actions if they exist
                        var funcName = "pluginaction_"+menuItem.itemId;
                        if (eval("typeof " + funcName + " == 'function'")) {
                            eval(funcName+"()");
                        }else {
                            //we only want to call if we are not calling another function
                            //as that other function will handle when it wants to call the plugin action method
                            packageemanager.plugincallaction(menuItem.itemId);
                        }
                    });
                    pluginActionMenu.addMenuItem(comboitem);
                    count++;
                }
                if (count==0) {
                    $('#plugindropdown').hide();
                } else {
                    $('#plugindropdown').show();
                }
            },
            params: {
                id:packageemanager.package_id
            }
        });
    }

    packageemanager.plugincallaction = function(itemid,args)
    {
        
        if (args==null) {
            args = "";
        }
        
        packageemanager.loadingMask.show();
        Ext.Ajax.request({
            url: 'index.php?fuse=clients&action=callPluginAction',
            success: function(xhr) {
                json = ce.parseAjaxResponse(xhr);
                packageemanager.showManageSettingByType(packageemanager.activeTab);
                packageemanager.updateAvailablePluginActions();
                packageemanager.loadingMask.hide();
            },
            params: {
                id:packageemanager.package_id,
                actioncmd:itemid,
                additionalArgs: args
            }})
    }

    packageemanager.currentProductStore = new Ext.data.JsonStore({
        root:           'results',
        totalProperty:  'totalcount',
        idProperty:     'productid',
        remoteSort:     true,
        fields:     ['id','producttype','Permissions','producttypename','dateactivated','pluginname','hasplugin','productgroupname','productid','name','group','desc','renewal','signup','status','status_class','panels','productidentifier','productpluginlogo'],
        proxy:          new Ext.data.HttpProxy({
            url: 'index.php?fuse=clients&action=adminGetUserPackages&filteroncustomer=1'
        })
    });

    packageemanager.currentProductStore.on('load',function() {
        if (packageemanager.currentProductStore.data.length > 0) {
            packageemanager.productData = packageemanager.currentProductStore.getAt(0).data;
        } else {
            alert("error: didn't return product");
        }
         
        //show settings panels that are available
        //hide those that are not
        $(".vtab").each(function (index, domEle) {
            domEle.style.display = "none";
        });

        for (var i in packageemanager.productData.panels)
        {
            if(document.getElementById('settingtype_'+packageemanager.productData.panels[i]) != undefined) {
                document.getElementById('settingtype_'+packageemanager.productData.panels[i]).style.display = "";
            }
                                
            //lazy load any javascript for type specific settings
            if($.inArray(packageemanager.productData.panels[i],packageemanager.arrayOfLazyLoadingPanels) > -1) {
                LazyLoad.js([relativePath+'templates/admin/views/clients/packages/sharedjs/profile_product_'+packageemanager.productData.panels[i]+'.js'], function () {});
            }
        }
        //show any image and product identifier
        document.getElementById('productidentifier').innerHTML = "#"+packageemanager.package_id+" "+packageemanager.productData.productidentifier;
        document.getElementById('productidentifier-type').innerHTML = packageemanager.productData.producttypename;
        document.getElementById('productidentifier-date').innerHTML = packageemanager.productData.dateactivated;
            
        if (packageemanager.productData.productpluginlogo != "") {
            document.getElementById('selectedproductlogo').style.display = "";
            document.getElementById('selectedproductlogo').src = relativePath+"plugins/"+packageemanager.productData.productpluginlogo;
        } else {
            document.getElementById('selectedproductlogo').style.display = "none";
        }
        
        //select product from dropdown list after we load new data
        packageemanager.productlistcombo.setValue(packageemanager.package_id);

        //TODO4.1 determine first if we need to show the options
        packageemanager.displayPluginOptions();
    });

    /**
     * Display Plugin dropdown list if the productData has a plugin
     */
    packageemanager.displayPluginOptions = function()
    {
        //determine if we have a plugin
        if( (packageemanager.productData.hasplugin) && ($('#divpluginactiondropdown').html() != "") ){
            //$('#plugindropdown').show();
            if($('#updateviaplugin').length > 0) {

                // Change the label on the update package checkbox
                if(packageemanager.productData.producttype == 3) {
                     $('#performonserver_wrapper >span').text('Update at Registrar if necessary');
                } else {
                    $('#performonserver_wrapper >span').text($('#fieldblock_updateviaplugin >dt>label').text());
                }

                 $('#performonserver_wrapper').show();
		 $('#performonserver').attr('checked', true);
		 $('#accountnotonserverwarning').hide();

                 //alert(dump(packageemanager.productData));

                 // Show the hidden domain tabs
                 document.getElementById('settingtype_domaincontactinfo').style.visibility = 'visible';
                 document.getElementById('settingtype_hostrecords').style.visibility = 'visible';
                 document.getElementById('settingtype_nameservers').style.visibility = 'visible';

            } else if($('#accountnotonserver').length > 0) {
                 $('#accountnotonserverwarning >div').text($('#fieldblock_accountnotonserver >dt>label').text());
                 $('#accountnotonserverwarning').show();
                 $('#performonserver').attr('checked', false);
            } else {
                $('#performonserver_wrapper').hide();
                $('#accountnotonserverwarning').hide();
		$('#performonserver').attr('checked', false);
            }
        } else if (packageemanager.productData.hasplugin){
            plugindiv = $("<div id='plugindropdown' style='position:relative;top:-2px;display:none;'></div>");
            $('#divpluginactiondropdown').append(plugindiv);
            new Ext.Button({
                id : 'btnpluginoptionbuttons',
                renderTo: 'plugindropdown',
                defaultType: 'splitbutton',
                arrowAlign: 'right',
                text: 'Plugin Options',
                split: true,
                cls: 'x-box-text-small',
                border:false,
                menu: pluginActionMenu = new Ext.menu.Menu({
                    id: 'pluginactiondropdownmenu',
                    enableScrolling:false,
                    shadow:false
                }),
                layout: 'anchor'
            });
            if($('#updateviaplugin').length > 0) {
                $('#performonserver_wrapper >span').text($('#fieldblock_updateviaplugin >dt>label').text());
                 $('#performonserver_wrapper').show();
				 $('#performonserver').attr('checked', true);
				 $('#accountnotonserverwarning').hide();
            } else if($('#accountnotonserver').length > 0) {
                 $('#accountnotonserverwarning >div').text($('#fieldblock_accountnotonserver >dt>label').text());
                 $('#accountnotonserverwarning').show();
				 $('#performonserver').attr('checked', false);
            } else {
                $('#performonserver_wrapper').hide();
                $('#accountnotonserverwarning').hide();
				$('#performonserver').attr('checked', false);
            }
        }else {
            //check to see if dropdown plugin exists and if so remove it
            if($('#divpluginactiondropdown').html() != "") {
                $('#plugindropdown').hide();
            }
            $('#performonserver_wrapper').hide();
            $('#accountnotonserverwarning').hide();
			$('#performonserver').attr('checked', false);
        }
    }

    /* switch viewe to grid that lists all products */
    shiftProductViewToAll = function()
    {
        packageemanager.package_id = 0;
        document.getElementById("domains-grid-header").style.display = "";
        //document.getElementById("domains-grid").style.display = "";
        document.getElementById("selected-product").style.display = "none";
    }

    packageemanager.shiftProductViewForId = function(id)
    {
        //update global selected package_id
        packageemanager.package_id = id;
        packageemanager.currentProductStore.load({
            params:{
                id:id,
                typeid:"groupinfo"
            },
            callback:packageemanager.showManageSettingByType
        });
        
        document.getElementById('userPackageId').value = id;
        document.getElementById("domains-grid-header").style.display = "none";
        //document.getElementById("domains-grid").style.display = "none";
        document.getElementById("selected-product").style.display = "";
    }
    //check to see if we passed product via url
    if (shiftToProduct > 0) {
        packageemanager.shiftProductViewForId(shiftToProduct);
    }

    /* Stores used for setting types */
    packageemanager.product_store_general = new Ext.data.JsonStore({
        id :    "product_store_general",
        root :  "productFields",
        totalProperty:  'totalcount',
        baseParams: {
            productgroup_id:0, 
            getCountriesValues: 1
        },
        idProperty: 'id',
        remoteSort: true,
        fields: ['id','name','fieldtype','vtype','value','width','selectfirstonblank','addrowdeletebtn','addrowdeletefnc','ischangeable','listener','isrequired','ishidden','dropdownoptions'],
        proxy:  new Ext.data.HttpProxy({
            url:  'index.php?fuse=clients&action=adminGetClientProductFields'
        })
    });

    packageemanager.loadingMask = new Ext.LoadMask('selected-product', {
        store:packageemanager.product_store_general,
        msg:"Please wait..."
    },packageemanager.product_store_general);

    Ext.get('btnUpdateProduct').on('click', function(){
        errors = false;
        var settingsForm = new Ext.form.BasicForm('productsettingsform');
        //loop through the html form's elements
        //checks to see if those that are Extjs objects validate
        for (var key in settingsForm.getValues()) {
            isctrl = false;
            if (Ext.type(Ext.getCmp(key))){
                isctrl = true;
            }else if(Ext.type(Ext.getCmp("ctrl"+key))){
                isctrl = true;
                key = "ctrl"+key;
            }

            if (isctrl && !Ext.getCmp(key).isValid()){
                if ($('#'+key).is(":reallyvisible")) {
                    errors = true;
                }
            }
        }
        //if errors return and show message
        if(errors) {
            Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
            return;
        }
        packageemanager.loadingMask.show();
        settingsForm.submit({
            params: {
                settingtype: packageemanager.viewingSettingPanel
            },
            success: function(form, action) {
                packageemanager.entries_store.load(); //to make sure grid and dropdown update their values
                packageemanager.loadingMask.hide();
                if (action.result.message!="") {
                    ce.msg(action.result.message);
                }else {
                    ce.msg("Settings Updated Successfully");
                }
                //need to check if identier changed and if so
                //get product general information again
                if (action.result.doActions.productidentifierchanged) {
                    packageemanager.currentProductStore.load({
                        params:{
                            id:packageemanager.package_id
                        }
                    });
                }
                //check to see if we need to update plugin dropdown list
                if ((action.result.doActions.productpluginneedsupdating) && (packageemanager.productData.hasplugin) ){
                    packageemanager.updateAvailablePluginActions();
                }

                packageemanager.showManageSettingByType(packageemanager.activeTab);

                /*
                //we need to clear all validation issues
                for (var key in settingsForm.getValues()) {
                    if (Ext.type(Ext.getCmp(key))){
                        Ext.getCmp(key).clearInvalid();
                    }else if(Ext.type(Ext.getCmp("ctrl"+key))){
                        Ext.getCmp("ctrl"+key).clearInvalid();
                    }
                }*/

            },
            failure: function(form,action){
                packageemanager.loadingMask.hide();
                Ext.Msg.alert('Action Failed',action.result.message);
            }
        });
    });
    
    //listener function for type of data being returned for the package
    //I need to return some HTML for a field pulled from fields callback
    packageemanager.returnFieldHTML = function(records,options,success)
    {

        var selectListeners = new Array();
        var clickListeners = new Array();
        var deleteRowListeners = new Array();
        
        var ctrl;
        var allFieldsDisabled = true;
        for(var iterator = 0; iterator < packageemanager.product_store_general.data.length; iterator++){
            var isComboType = false
            var hideElementStyle = "";
            var currentFieldData = packageemanager.product_store_general.getAt(iterator).data;
            var currentFieldValue = currentFieldData.value;
            var allowBlankValue = true;
            var isDisabled = true;
            var selectFirstOnBlank = true;

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

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

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

            if (typeof(currentFieldData.ishidden) != "undefined"){
                if(currentFieldData.ishidden == 1) {
                    hideElementStyle = "style='display:none;'";
                }
            }

            var createHiddenTypeField = false;
            var controlid = currentFieldData.id;
            if (isInteger(currentFieldData.id)) {
                controlid = 'CT_' + currentFieldData.id;
                createHiddenTypeField = true;
            }
            
            switch(currentFieldData.fieldtype){
                case '52':
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    $('#selectedproduct-view').append(String.format('<div id="fieldblock_{1}" style="display:none;" class="fieldblock"><dt><label>{0}</label></dt><dd class="ddelement" style="width:270px;"><div  style="float:left;" id="textfield_{1}"></div><div style="float:left;padding-left:5px;" id="deleterowbtn_{1}"></div></dd></div>',currentFieldData.name,currentFieldData.id));
                    ctrl = new Ext.form.TextField({
                        id:               controlid,
                        name:             controlid,
                        value:            currentFieldValue,
                        renderTo:         'textfield_' + currentFieldData.id
                    });
                    break;
                case '0':   // typeTEXTFIELD
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    $('#selectedproduct-view').append(String.format('<div id="fieldblock_{1}" '+hideElementStyle+' class="fieldblock"><dt><label>{0}</label></dt><dd class="ddelement" style="width:270px;"><div  style="float:left;" id="textfield_{1}"></div><div style="float:left;padding-left:5px;" id="deleterowbtn_{1}"></div></dd></div>',currentFieldData.name,currentFieldData.id));
                    ctrl = new Ext.form.TextField({
                        id:               controlid,
                        name:             controlid,
                        width:            width,
                        disabled:         isDisabled,
                        border:           false,
                        value:            currentFieldValue,
                        allowBlank:       allowBlankValue,
                        validationEvent: false,
                        blankText:        lang("This field is required"),
                        renderTo:         'textfield_' + currentFieldData.id
                    });
                    break;
                case '10': //typeTextArea
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    $('#selectedproduct-view').append(String.format('<div id="fieldblock_{1}" '+hideElementStyle+' class="fieldblock"><dt><label>{0}</label></dt><dd class="ddelement" style="width:270px;"><div  style="float:left;" id="textarea_{1}"></div><div style="float:left;padding-left:5px;" id="deleterowbtn_{1}"></div></dd></div>',currentFieldData.name,currentFieldData.id));
                    ctrl = new Ext.form.TextArea({
                        id:     controlid,
                        name:   controlid,
                        width:            width,
                        disabled:         isDisabled,
                        border:           false,
                        validationEvent:  false,
                        allowBlank:       allowBlankValue,
                        blankText:        lang("This field is required"),
                            value:            currentFieldValue,
                        renderTo:         'textarea_' + currentFieldData.id
                    });
                    break;
                case '1':   // typeYESNO
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    isComboType = true;
                    storeObject = [[0,lang('No')],[1,lang('Yes')]];
                    $('#selectedproduct-view').append(String.format('<div id="fieldblock_{1}" '+hideElementStyle+'  class="fieldblock"><dt><label>{0}</label></dt><dd class="ddelement" style="width:270px;"><div id="yesno_{1}"></div></dd></div>',currentFieldData.name,currentFieldData.id));
                    ctrl = new Ext.form.ComboBox({
                            id:               'ctrl' + controlid,
                            name:             controlid,
                            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,
                            renderTo:         'yesno_' + currentFieldData.id
                        });

                        if ( (currentFieldValue=="") || (currentFieldValue==null)) {
                            Ext.getCmp('ctrl' + controlid).setValue(Ext.getCmp('ctrl' + controlid).getStore().getAt(0).data.field1);
                        }

                    break;
                case '6':   // typeCOUNTRY
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    isComboType = true;
                    storeObject = currentFieldData.dropdownoptions;
                    $('#selectedproduct-view').append(String.format('<div id="fieldblock_{1}" '+hideElementStyle+' class="fieldblock"><dt><label>{0}</label></dt><dd class="ddelement" style="width:270px;"><div id="country_{1}"></div></dd></div>',currentFieldData.name,currentFieldData.id));
                    ctrl = new Ext.form.ComboBox({
                            id:               controlid,
                            name:             controlid,
                            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,
                            renderTo:         'country_' + currentFieldData.id
                        });
                        if ( (currentFieldValue=="") || (currentFieldValue==null)) {
                            Ext.getCmp(controlid).setValue(Ext.getCmp(controlid).getStore().getAt(0).data.field1);
                        }
                    break;
                case '30': //product status
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    isComboType = true;
                    storeObject = currentFieldData.dropdownoptions;
                    $('#selectedproduct-view').append(String.format('<div id="fieldblock_{1}" '+hideElementStyle+' class="fieldblock"><dt><label>{0}</label></dt><dd class="ddelement" style="width:270px;"><div id="dropdown_{1}"></div></dd></div>',currentFieldData.name,currentFieldData.id));
                    ctrl = new Ext.form.ComboBox({
                            id:               'ctrl' + controlid,
                            name:             controlid,
                            hiddenName:       controlid,
                            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,
                            renderTo:         'dropdown_' + currentFieldData.id
                        });
                        if (!packageemanager.productData.Permissions.changestatus) {
                           Ext.getCmp('ctrl' + controlid).setDisabled(true);
                        }
                    break;
                case '9': //dropdown
                    width = (currentFieldData.width) ? currentFieldData.width : 200;
                    isComboType = true;
                    if (currentFieldData.vtype == ""){
                        currentFieldData.vtype = null;
                    }
                    storeObject = currentFieldData.dropdownoptions;
                    $('#selectedproduct-view').append(String.format('<div id="fieldblock_{1}" '+hideElementStyle+' class="fieldblock"><dt><label>{0}</label></dt><dd class="ddelement" style="width:270px;"><div id="dropdown_{1}"></div></dd></div>',currentFieldData.name,currentFieldData.id));
                    ctrl = new Ext.form.ComboBox({
                        id:               "ctrl"+controlid,
                        name:             controlid,
                        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" ext: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,
                        renderTo:         'dropdown_' + currentFieldData.id
                    });

                    //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);
                    }

                    break;
                 case '15':  //  typeDATE
                    if (currentFieldValue != '' && currentFieldValue != '00/00/0000') {
                        //currentFieldValue = (new Date(Date.parse(currentFieldValue))).dateFormat(gDateFormat);
                        currentFieldValue = currentFieldValue;
                    }else {
                        currentFieldValue = '';
                    }
                    $('#selectedproduct-view').append(String.format('<div id="fieldblock_{1}" '+hideElementStyle+' class="fieldblock"><dt><label>{0}</label></dt><dd class="ddelement" style="width:270px;"><div id="date_{1}"></div></dd></div>',currentFieldData.name,currentFieldData.id));
                    ctrl = new Ext.form.DateField({
                            id:               controlid,
                            name:             controlid,
                            height:           "5px",
                            selectOnFocus:    true,
                            width:            200,
                            format:           gDateFormat,
                            disabled:         isDisabled,
                            value:            currentFieldValue,
                            allowBlank:       false,
                            validationEvent: false,
                            blankText:        lang("This field is required"),
                            renderTo:         'date_' + currentFieldData.id
                    });
                    if ( (currentFieldValue=="") || (currentFieldValue==null)) {
                        Ext.getCmp(controlid).setValue(new Date());
                    }
                    break;
                 case '53':
                    width = (currentFieldData.width) ? currentFieldData.width : 20;
                    $('#selectedproduct-view').append(String.format('<div id="fieldblock_{1}" '+hideElementStyle+' class="fieldblock"><dt><label>{0}</label></dt><dd class="ddelement" style="width:290px;"><div  style="float:left;" id="textfield_{1}"></div><div style="float:left;padding-left:5px;" id="deleterowbtn_{1}"></div></dd></div>',currentFieldData.name,currentFieldData.id));
                    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"),
                        renderTo:         'textfield_' + currentFieldData.id
                    });

                    break;
                 case '49':
                     //default to length of 380 as most fields are that length
                     width = (currentFieldData.width) ? currentFieldData.width : 380;
                     $('#selectedproduct-view').append(String.format('<div id="fieldblock_{0}" '+hideElementStyle+' class="fieldblock"><dt><dd style="padding-left:0px !important;"><div id="btn_{0}"></div></dd></dt></div>',currentFieldData.id));
                     ctrl = new Ext.Button({
                         id: controlid,
                         name: controlid,
                         renderTo : 'btn_' + currentFieldData.id,
                         width: width,
                         text: currentFieldValue
                     });
                     break;
                 case '50':
                     //dnsvalue = currentFieldValue.split("|");
                     $('#selectedproduct-view').append(String.format('<div id="fieldblock_{0}" '+hideElementStyle+' class="fieldblock"><dt><dd style="padding-left:0px !important;"><div style="float:left;" id="dnshostname_{0}"></div><div style="float:left;padding-left:5px;" id="dnshosttype_{0}"></div><div style="float:left;padding-left:5px;" id="dnshostaddress_{0}"></div><div style="float:left;padding-left:5px;" id="deleterowbtn_{0}"></div></dd></dt></div>',currentFieldData.id));
                     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"),
                        renderTo:         'dnshostname_' + currentFieldData.id
                    });
                    storeObject = [['A','A'],['MXE','MXE'],['MX','MX'],['CNAME','CNAME'],['URL','URL'],['FRAME','FRMAE'],['TXT','TXT']];
                    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,
                        renderTo:         'dnshosttype_' + currentFieldData.id
                    });

                    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"),
                        renderTo:         'dnshostaddress_' + currentFieldData.id
                    });
                    break;

            }

            //add hidden for type if we have a custom field
            if (createHiddenTypeField) {
                $('#selectedproduct-view').append("<div id='hiddentype_"+controlid+"'></div>");
                new Ext.form.Hidden ({
                    id: 'CTT_' + currentFieldData.id,
                    name : 'CTT_' + currentFieldData.id,
                    value: currentFieldData.fieldtype,
                    renderTo: 'hiddentype_'+controlid
                });
            }

            //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)')
                     }
                 });
            }
            
        }

        //if returned zero store items
        //if ((packageemanager.product_store_general.data.length == 0) || (!canaddeditpackages)) {
        if (packageemanager.product_store_general.data.length == 0) {
            $('#selectedproduct-view').append("<div style='clear:both;padding-top:10px;width:400px;color:gray;'><center>" + lang('No items found') + "</center></div>");
            document.getElementById('btnUpdateProduct').style.display = "none";
            document.getElementById('btnoptionsseperator').style.display = "none";
        } else {
            //check to see if all fields are disabled... if so remove update btn
            if (allFieldsDisabled){
                document.getElementById('btnUpdateProduct').style.display = "none";
                document.getElementById('btnoptionsseperator').style.display = "none";
            } else {
                $('#selectedproduct-view').append("<div style='clear:both;padding-top:10px;'></div>");
                document.getElementById('btnUpdateProduct').style.display = "";
                document.getElementById('btnoptionsseperator').style.display = "";
            }
        }

        //call dispatch function for the newley selected setting panel (if exists)
        var funcName = packageemanager.viewingSettingPanel+"_dispatch";
        if (eval("typeof " + funcName + " == 'function'")) {
            eval(packageemanager.viewingSettingPanel+"_dispatch()");
        }

        //draw plugin btn if we have a plugin
        //TODO4.1 determine first if we need to show these options
        packageemanager.displayPluginOptions();
    }

    /**
     * Toggle recurring billing dropdown
     */
    function billingToggleRecurring()
    {
        $('.fieldblock').each(function (index, domEle) {
             if (domEle.id != "fieldblock_recurring") {
                if (Ext.getCmp('ctrlrecurring').getValue() == 1) {
                    domEle.style.display = "";
                } else {
                    domEle.style.display = "none";
                }
             }
        });

        if (Ext.getCmp('ctrlrecurring').getValue() == 1) {
            //set first item in dropdown
            Ext.getCmp('ctrlbillingcycle').setValue(Ext.getCmp('ctrlbillingcycle').getStore().getAt(0).data.field1);
        } else {
            //remove validation
        }
        
        billingChangedBillingCycle();
    }

    function billingChangedBillingCycle() {
        Ext.Msg.alert('Warning', 'Changing the Recurring or Billing Cycle of the product can affect its addons.<br>Please make sure to update the addons after finishing updating the billing information.');
    }

});


