//namespace for packagemanager for userpackages
var packageemanager = {};
packageemanager.package_id = 0;
packageemanager.arrayOfLazyLoadingPanels = ["hosting","domaininfo","hostrecords","nameservers", 'certinfo']; //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" 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 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 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) {
                ce.lazyLoad([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());
                }
                if(packageemanager.productData.producttype == 2 ) {
                    $('#performonserver_wrapper').hide();
                } else {
                    $('#performonserver_wrapper').show();
                    $('#performonserver').attr('checked', true);
                    $('#accountnotonserverwarning').hide();
                }



                 // 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)
    {
        for(var iterator = 0; iterator < packageemanager.product_store_general.data.length; iterator++){
            customFields.getMarkup(packageemanager.product_store_general.getAt(iterator).data, function(control, data, idLabel) {
                customFields.defaultRenderer(control, data, idLabel, 'selectedproduct-view', $('#selectedproduct-view'));
            });
        }

        //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 (customFields.getAllFieldsDisabled()){
                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();
    }

  



});


