

Ext.namespace('ClientExec'); //define namespace with some 'name'

ClientExec.ProductSettings = function(){

        /* Private Variables */


        /* Used By All Tabs */
        var packageWin;
        var myMask; 
        var productId;
        var update = false;
        var windowWidth = 744;
        var windowHeight = 580;
        var titleText;
        var addonsRendered = false;
        var closing = false;
        var okForServerPluginAlert = false; // work around for documented combobox bug in which the "change" event fires when window is clicked, moved, closed etc...

        /* General Settings Tab Variables */
        var txtBillingCyclesMonthlyAmount;
        var ckBillingCyclesMonthlyAmountAllowInSignup;
        var txtBillingCyclesQuarterlyAmount;
        var billingCyclesRowMonthlySignup;
        var ckBillingCyclesQuarterlyAmountAllowInSignup;
        var billingCyclesRowQuarterlySignup;
        var txtBillingCyclesSemiAnnualAmount;
        var ckBillingCyclesSemiAnnualAmountAllowInSignup;
        var txtBillingCyclesAnnualAmount;
        var ckBillingCyclesAnnualAmountAllowInSignup;
        var billingCyclesRowSemiAnnualSignup;
        var ckBillingCyclesBiennialAmountAllowInSignup;
        var billingCyclesRowBiennialSignup;
        var billingCyclesRowSetupPrice;
        var txtBillingCyclesSetupPrice;
        var ckBillingCyclesPackageIsTaxable;
        var billingCyclesRowPackageIsTaxable;
        var billingCyclesPanel;
        var billingCyclesRowAnnualSignup;        
        var txtGeneralSettingsPackageName;
        var generalSettingsPackageName;
        var productTypesStore;
        var cboGeneralSettingsPackageType;
        var generalSettingsPackageType;
        var generalSettingsSignupURL;
        var lblGeneralSettingsSignupURL;
        var ckGeneralSettingsShowPackageInSignup;
        var generalSettingsShowPackageInSignup;
        var ckGeneralSettingsAllowDirectLink;
        var generalSettingsAllowDirectLink;
        var emailSettingsUsePackageTypeWelcomeEmail;
        var txtEmailSettingsSubject;
        var emailSettingsSubject;
        var htmlEditProductDescription;
        var txtProductWelcomeEmail;
        var htmlEditProductWelcomeEmail;
        var productWelcomeEmailTabs;
        var txtBillingCyclesBiennialAmount;
        var ckEmailSettingsUsePackageTypeWelcomeEmail;
        var ckEmailSettingsSendWelcomeEmail;
        var tabPagePackageGeneral;
        var productTabs;
        var productType="";
        var serverIds="";       
        var pluginCollection;       

        /* addon tab variables*/
        var addon;
        var addonStore;
        var addonGridView;       
        var addonStyleStore;
        var cboProductAddonStyle
        var lovComboAddons;
        var addonLovComboStore;
        var productAddonStyle=0;       
        var addonGrid;

        /* server tab variables*/
        var hostManagerPluginTable;
        var serverStore;
        var hostManagerStore;
        var cboSelectServerHostManager;
        //var synchServerCombos;
        var serversMultiSelectPanel;
        var serversNoticePanel;
        var defaultWidth = 180;
        var tabPageAdvanced;


        /* Form Variables*/
        var frmPackageTab;
        var frmPackage;

        // collection class
        function Collection() {
            this.collection = {};
            var data = [];

            this.toArray = function(){

                var a = [];
                for (var ii = 0; ii < data.length; ++ii) {
                        if (data[ii] != null) {
                            a.push(this.get(data[ii]));
                        }
                    }
                return a;
            }

            this.getLength = function() { return data.length;}

            this.get = function(property){

                if (this.exists(property)){
                    return this.collection[property];
                }
                return null;
            }

            this.add = function(property, value) {
                if (!this.exists(property)) {
                    this.collection[property] = value;
                    data.push(property);
                }
            }

            this.remove = function(property) {
                this.collection[property] = null;
                var ii = data.length;
                while (ii-- > 0) {
                    if (data[ii] == property) {
                        data[ii] = null;
                        break;
                    }
                }
            }

            this.removeAll = function() {
                this.collection = {};
                data = [];
            }

            this.toString = function() {
                var output = [];
                for (var ii = 0; ii < this.data.length; ++ii) {
                    if (data[ii] != null) {
                        output.push(this.collection[data[ii]]);
                    }
                }
                return output;
            }

            this.getKeys = function() {
                var keys = [];
                    for (var ii = 0; ii < data.length; ++ii) {
                        if (data[ii] != null) {
                            keys.push(data[ii]);
                        }
                    }
                return keys;
            }

            this.update = function(property, value) {
                if (value != null) {
                    this.collection[property] = value;
                }
                var ii = this.data.length;
                while (ii-- > 0) {
                    if (data[ii] == property) {
                        data[ii] = null;
                        data.push(property);
                        break;
                    }
                }
            }

            this.exists = function(property) {
                return this.collection[property] != null;
            }


         }

         /* Private Variables End */

        /* Private Medthods*/
        function setWindowTitle(){

             var title =  titleText + ' - ' +  txtGeneralSettingsPackageName.getValue();
             win.setTitle(title);

        }

        function TableTypeWindow (update){
            if(this instanceof TableTypeWindow){
                this.update = update;
                this.CreateWindow = createWindow;
                this.PopulateFields = populateFields;
            }else{
                return new TableTypeWindow();
            }
        }

        function populateFields(id) {
        //debugger;

            productStore = new Ext.data.JsonStore({
                id:             'productStore',
                root:           'thePackage',
                totalProperty:  'totalcount',
                idProperty:     'packageId',
                remoteSort:     false,
                baseParams:     {
                                    packageid: id
                                },
                fields:         [
                                    'packageId',
                                    'welcomeEmailSubject',
                                    'signupURL',
                                    'packageName',
                                    'allowInSignup',
                                    'allowDirectLink',
                                    'packageGroupId',
                                    'priceMonthly',
                                    'priceMonthly_checked',
                                    'priceQuarterly',
                                    'priceQuarterly_checked',
                                    'priceSemiannual',
                                    'priceSemiannual_checked',
                                    'priceYearly',
                                    'priceYearly_checked',
                                    'price2Years',
                                    'price2Years_checked',
                                    'priceSetup',
                                    'taxable',
                                    'style',
                                    'packageDescription',
                                    'useDefaultEmailChecked',
                                    'sendWelcomeEmailChecked',
                                    'welcomeEmailDisplay',
                                    'welcomeEmailHTML',
                                    'welcomeEmailText',
                                    'clientType',
                                    'topLevelDomainIds',
                                    'serverIds'
                                ],
                proxy: new Ext.data.HttpProxy({
                    url: 'index.php?fuse=admin&action=Admin_GetProduct&packageid=' + id
                })
            });


            productStore.on('load',function(){

                var currentPackage = productStore.reader.jsonData.thePackage[0];

                productAddonStyle = currentPackage.style;               

                txtGeneralSettingsPackageName.setValue(currentPackage.packageName);
                setWindowTitle();

                ckGeneralSettingsShowPackageInSignup.setValue(currentPackage.allowInSignup);

                ckGeneralSettingsAllowDirectLink.setValue(currentPackage.allowDirectLink);

                lblGeneralSettingsSignupURL.html = "<a href='" + currentPackage.signupURL + "'>" + currentPackage.signupURL + "</a>";
                
                productType = currentPackage.packageGroupId;
                if (cboGeneralSettingsPackageType.getStore().data.length>0){

                    cboGeneralSettingsPackageType.setValue(parseInt(currentPackage.packageGroupId));
                    loadAddonsCombo();
                }
                else {
                    cboGeneralSettingsPackageType.getStore().load();
                }

                txtBillingCyclesMonthlyAmount.setValue(currentPackage.priceMonthly);
                ckBillingCyclesMonthlyAmountAllowInSignup.setValue(currentPackage.priceMonthly_checked);

                txtBillingCyclesQuarterlyAmount.setValue(currentPackage.priceQuarterly);
                ckBillingCyclesQuarterlyAmountAllowInSignup.setValue(currentPackage.priceQuarterly_checked);

                txtBillingCyclesSemiAnnualAmount.setValue(currentPackage.priceSemiannual);
                ckBillingCyclesSemiAnnualAmountAllowInSignup.setValue(currentPackage.priceSemiannual_checked);

                txtBillingCyclesAnnualAmount.setValue(currentPackage.priceYearly);
                ckBillingCyclesAnnualAmountAllowInSignup.setValue(currentPackage.priceYearly_checked);

                txtBillingCyclesBiennialAmount.setValue(currentPackage.price2Years);
                ckBillingCyclesBiennialAmountAllowInSignup.setValue(currentPackage.price2Years_checked);

                txtBillingCyclesSetupPrice.setValue(currentPackage.priceSetup);

                ckBillingCyclesPackageIsTaxable.setValue(currentPackage.taxable);

                htmlEditProductDescription.setValue(decodeURIComponent(currentPackage.packageDescription));

                htmlEditProductWelcomeEmail.setValue(decodeURIComponent(currentPackage.welcomeEmailHTML));

                txtProductWelcomeEmail.setValue(currentPackage.welcomeEmailText);

                txtEmailSettingsSubject.setValue(currentPackage.welcomeEmailSubject);

                myMask.hide();
                win.show(this);
                if (!ckGeneralSettingsAllowDirectLink.checked){

                    generalSettingsSignupURL.hide();
                }


                ckEmailSettingsUsePackageTypeWelcomeEmail.setValue(currentPackage.useDefaultEmailChecked);
                ckEmailSettingsSendWelcomeEmail.setValue(currentPackage.sendWelcomeEmailChecked);
        
            
                if (currentPackage.serverIds!=""){             
                    selectProductServerRows(currentPackage.serverIds);
                }

            });

           selectProductServerRows = function(serverids){
              
               if (serverids!=""){
                  
                   if (lovComboProductServers.getStore().data.length>0){
                       lovComboProductServers.setValue(serverids);
                       var vals = lovComboProductServers.getCheckedValue();
                       //debugger;
                       synchServerCombos(false);
                   }
                   else {
                       serverIds = serverids;
                       lovComboProductServers.getStore().load();
                   }
               }
           };


            productStore.on('loadexception',function(){

                myMask.show();                
                Ext.MessageBox.alert('Error Message', "Error Loading Data");

            });
            
            productStore.load();

        }

        function loadAddonsCombo(){
            var addonUrl="";
            addonLovComboStore.removeAll();

            if (update || productType!=""){              
                addonLovComboStore.load({
                    url: addonUrl,
                    params: {
                        productgroup_id:productType
                    }
                });
            }else {               
                addonLovComboStore.load({
                    url: addonUrl,
                    params: {
                        inallgroups: "1"
                    }
                });
            }
        }

        function loadSuccessful(form, action){

            /**
            * The function to call when the response from the server was a successful
            * attempt (load in this case). The function is passed the following parameters:
            *
            * @param {Ext.form.BasicForm} form The form that requested the action.
            * @param {Ext.form.Action} action The Action class.
            * The result property of this object may be examined to perform custom postprocessing.
            */

            // Decodes (parses) a JSON string to an object. If the JSON is invalid,
            // this function throws a SyntaxError.
            //debugger;

            // use below to get at data returned
            //var object = Ext.util.JSON.decode(action.response.responseText);
            //debugger;
            //Ext.MessageBox.alert('Confirm', object.data.enable_delete);


        }

        function loadFailed(form, action) {
            /**
             * The function to call when the response from the server was a failed
             * attempt (load in this case), or when an error occurred in the Ajax
             * communication. The function is passed the following parameters:
             * @param {Ext.form.BasicForm} form The form that requested the action.
             * @param {Ext.form.Action} action The Action class.
             * If an Ajax error occurred, the failure type will be in failureType.
             * The result property of this object may be examined to perform custom postprocessing.
             *
             * A failed attempt (load in this case) response from the server will be:
             * {success: false, message: 'Failure message to be displayed.'}
             */
            var failureMessage = "Error occurred trying to retrieve data.";

            // Failure type returned when no field values are returned in the
            // response's data property or the successProperty value is false.
            if (action.failureType == Ext.form.Action.LOAD_FAILURE) {

                // Error on the server side will include an error message in
                // the response.

                // Decodes (parses) a JSON string to an object. If the JSON is invalid,
                // this function throws a SyntaxError.
                var object = Ext.util.JSON.decode(action.response.responseText);

                failureMessage = object.data.message;
            }
            // Failure type returned when a communication error happens when
            // attempting to send a request to the remote server.
            else if (action.failureType == Ext.form.Action.CONNECT_FAILURE) {

                // The XMLHttpRequest object containing the
                // response data. See http://www.w3.org/TR/XMLHttpRequest/ for
                // details about accessing elements of the response.
                failureMessage = "Please contact support with the following: " +
                    "Status: " + action.response.status +
                    ", Status Text: " + action.response.statusText;
            }

            Ext.MessageBox.alert('Error Message', failureMessage);
        }

        function validateFields(fld,msg,allmsgs){
            var newline = "<br>";
            if (!fld.validate()){
                if (allmsgs.str!=''){

                    allmsgs.str += newline + lang(msg);
                }
                else allmsgs.str = lang(msg);
            }
        }

        function onCompleteAction(responseObj){
           
            var data = Ext.util.JSON.decode(responseObj.responseText);
            if(data.error){
                if(data.message){
                    Ext.MessageBox.alert(lang("Errors"), data.message);
                }else{
                    Ext.MessageBox.alert(lang("Errors"), "There was an error performing this action");
                }
                return;
            }else if(data.message){
                msg(data.message,"");
            }else{
                msg(lang("Action have been performed"),"");
            }
            
           
            grid = Ext.getCmp("productsGrid");
            if(grid!=null){

                grid.getStore().load({params:{start:0}});
               
            }
            
            win.close();

        }

        function deleteProduct(url){

            new Ajax.Request(url,
                {
                    parameters: 'productid=' + encodeURIComponent(productId),
                    onComplete: onCompleteAction

                }
            );
        }

        function getPluginPostParams(){

            var pluginVarParms = "";
            var respObjKeys = pluginCollection.getKeys();
            for (var i = 0; i<respObjKeys.length;i++){

                var respObj = pluginCollection.get(respObjKeys[i]);

                if (respObj.pluginInputVarDisabled==0 && respObj.inputValue!==null){

                    pluginVarParms += '&' + respObj.inputName + '=' + respObj.inputValue;
                }

                if (respObj.package_vars){

                    for(var j=0;j<respObj.package_vars.length;j++){

                        if (respObj.package_vars[j].packageAttrInputType=="text" && respObj.package_vars[j].packageAttrFieldValue){
                            pluginVarParms  += '&' + respObj.package_vars[j].id + '=' + respObj.package_vars[j].packageAttrFieldValue;
                        }else if (respObj.package_vars[j].packageAttrInputType=="checkbox" && respObj.package_vars[j].packageAttrChecked!==null){
                            pluginVarParms  += '&' + respObj.package_vars[j].id + '=' + respObj.package_vars[j].packageAttrChecked;
                        }
                    }


                }else if (respObj.reseller_acl_fields){

                    for(var x=0;x<respObj.reseller_acl_fields.aclResourceLimitsfields.length;x++){

                        if (respObj.reseller_acl_fields.aclResourceLimitsfields[x].aclType=="text")
                            pluginVarParms  += '&' + respObj.reseller_acl_fields.aclResourceLimitsfields[x].id + '=' + respObj.reseller_acl_fields.aclResourceLimitsfields[x].aclValue;
                        else
                            pluginVarParms  += '&' + respObj.reseller_acl_fields.aclResourceLimitsfields[x].id + '=' + respObj.reseller_acl_fields.aclResourceLimitsfields[x].aclChecked;
                    }

                    for(var y=0;y<respObj.reseller_acl_fields.aclNonResourceLimitsfields.length;y++){

                        pluginVarParms  += '&' + respObj.reseller_acl_fields.aclNonResourceLimitsfields[y].id + '=' + respObj.reseller_acl_fields.aclNonResourceLimitsfields[y].aclOptionChecked;
                    }

                }

            }

            return pluginVarParms;
        }

        function addonHTMLEncode(row){

            
            row.description = encodeURIComponent(row.description);
            row.name = encodeURIComponent(row.name);
            row.plugin_var = encodeURIComponent(row.plugin_var);
            row.value = encodeURIComponent(row.value);

            return row;
        }

        function getAddonPostParms(){

            var parms = "";
            addonStore.commitChanges();
            if (addonStore.data.length>0){


                var addonArray = new Array(addonStore.data.length);
                for(var i=0;i<addonStore.data.length;i++){

                    // order the addons according to the store order
                    addonStore.data.items[i].data.order = i;
                    addonStore.commitChanges();
                    var row =  addonStore.data.items[i].data;

                    addonArray[i] =  addonHTMLEncode(row);

                }

                parms = "&addons=" + Ext.util.JSON.encode(addonArray);
            }
            else {
                // only send empty array if addons tab was rendered 
                // otherwise we don't know how many addons exist
                // for this product
                if (addonsRendered){
                    parms = "&addons=[]";
                }
            }



            return parms;

        }

        function saveUpdateProduct(type,url,waitMsg){


            //debugger;
            var message = {str: ''};

            // validate first tab
            validateFields(txtBillingCyclesMonthlyAmount,"Monthly Amount",message);
            validateFields(txtBillingCyclesQuarterlyAmount,"Quarterly Amount",message);
            validateFields(txtBillingCyclesSemiAnnualAmount,"Semi-Annual Amount",message);
            validateFields(txtBillingCyclesAnnualAmount,"Annual Amount",message);
            validateFields(txtBillingCyclesBiennialAmount,"Two Year Amount",message);
            validateFields(txtBillingCyclesSetupPrice,"Setup Price",message);

            validateFields(txtGeneralSettingsPackageName,"Product Name",message);
            validateFields(cboGeneralSettingsPackageType,"Product Type",message);

            var params =            'packageid='               + encodeURIComponent(productId)
                                   + '&planid='                     + encodeURIComponent(cboGeneralSettingsPackageType.getValue())
                                   + '&planname='                   + encodeURIComponent(txtGeneralSettingsPackageName.getValue())
                                   + '&price='                      + encodeURIComponent(txtBillingCyclesMonthlyAmount.getValue())
                                   + '&price1included='             + encodeURIComponent(ckBillingCyclesMonthlyAmountAllowInSignup.checked?'1':'0')

                                   + '&price3='                     + encodeURIComponent(txtBillingCyclesQuarterlyAmount.getValue())
                                   + '&price3included='             + encodeURIComponent(ckBillingCyclesQuarterlyAmountAllowInSignup.checked?'1':'0')

                                   + '&price6='                     + encodeURIComponent(txtBillingCyclesSemiAnnualAmount.getValue())
                                   + '&price6included='             + encodeURIComponent(ckBillingCyclesSemiAnnualAmountAllowInSignup.checked?'1':'0')

                                   + '&price12='                    + encodeURIComponent(txtBillingCyclesAnnualAmount.getValue())
                                   + '&price12included='            + encodeURIComponent(ckBillingCyclesAnnualAmountAllowInSignup.checked?'1':'0')

                                   + '&price24='                    + encodeURIComponent(txtBillingCyclesBiennialAmount.getValue())
                                   + '&price24included='            + encodeURIComponent(ckBillingCyclesBiennialAmountAllowInSignup.checked?'1':'0')

                                   + '&setup='                      + encodeURIComponent(txtBillingCyclesSetupPrice.getValue())
                                   + '&showpackage='                + encodeURIComponent(ckGeneralSettingsShowPackageInSignup.checked?'1':'0')
                                   + '&allowdirectlink='            + encodeURIComponent(ckGeneralSettingsAllowDirectLink.checked?'1':'0')
                                   + '&taxable='                    + encodeURIComponent(ckBillingCyclesPackageIsTaxable.checked?'1':'0')
                                   + '&style='                      + encodeURIComponent(cboProductAddonStyle.getValue())
                                   + '&description='                + encodeURIComponent(htmlEditProductDescription.getValue())
                                   + '&welcomeemail_subject='       + encodeURIComponent(txtEmailSettingsSubject.getValue())
                                   + '&welcomeemail_html='          + encodeURIComponent(htmlEditProductWelcomeEmail.getRawValue())
                                   + '&welcomeemail_text='          + encodeURIComponent(txtProductWelcomeEmail.getValue())
                                   + '&usedefaultwelcome='          + encodeURIComponent(ckEmailSettingsUsePackageTypeWelcomeEmail.checked?'1':'0')
                                   + '&sendwelcome='                + encodeURIComponent(ckEmailSettingsSendWelcomeEmail.checked?'1':'0');


            // get host manager plugin settings
            var pluginPostParams = getPluginPostParams();
           
            params += pluginPostParams;

            var addonPostParms = getAddonPostParms();

            params += addonPostParms;


            // get servers
            var servers = lovComboProductServers.getValue();

            params += '&lovComboProductServers=' + servers;

            if(message.str != ''){
                Ext.MessageBox.alert(lang("Errors"), lang("The following form field(s) were incomplete or incorrect") + ":<br><br>" + message.str + "<br><br>" + lang("Please complete or correct the form and submit again."));
                return;
            }else {

                 new Ajax.Request('index.php?fuse=admin&action=Admin_SaveProduct',
                    {
                         parameters: params,
                         onComplete: onCompleteAction
                    });
            }
        }

        function setDefaultsForAdd(){

            txtBillingCyclesMonthlyAmount.setValue(0.00);
            txtBillingCyclesQuarterlyAmount.setValue(0.00);
            txtBillingCyclesSemiAnnualAmount.setValue(0.00);
            txtBillingCyclesAnnualAmount.setValue(0.00);
            txtBillingCyclesBiennialAmount.setValue(0.00);
            txtBillingCyclesSetupPrice.setValue(0.00);

        }

        function moveAddonFromComboToGrid(){

            var curVal = lovComboAddons.getValue();
            
            if(curVal == ''){
                Ext.MessageBox.alert(lang("Notice"), lang("You must first select an addon from the list.<br>If your list is empty or you need to create more addons, you can do it in System Setup > Products > Addons"));
                return;
            }
            
            for(var i =0;i<addonLovComboStore.data.length;i++){
                var item = addonLovComboStore.data.items[i];
                var row = item.data;
                if (row.id==curVal){
                        var temp = new addon({
                                        id: row.id,
                                        name: row.name,
                                        description: row.description,
                                        plugin_var: row.plugin_var,
                                        order: row.order,
                                        taxable: row.taxable

                                        });
                       // remove item from Combo
                       addonLovComboStore.remove(item);
                       lovComboAddons.setValue('');

                       // add item to grid
                       addonStore.insert(addonStore.getCount(), temp);
                       addonGrid.getView().refresh(true);

                }
            }

        }

        function moveAddonFromGridToCombo(item){

                var row = item.data;

                var temp = new addon({
                                id: row.id,
                                name: row.name,
                                description: row.description,
                                plugin_var: row.plugin_var,
                                order: row.order,
                                taxable: row.taxable

                                });

               // remove from grid
               addonStore.remove(item);
               addonGrid.getView().refresh(true);

               // add to combo
               addonLovComboStore.insert(0, temp);
               lovComboAddons.setValue(row.id);
        }

        function createWindow(update,currentPackageId){
            currentPackageId = currentPackageId || "-1";
            var requesturl;
            var buttonText;
           
            var waitMessage;

            if(update){
                requesturl = 'index.php?fuse=admin&action=Admin_UpdateProduct';
                buttonText = lang('Update');
                titleText = '&nbsp;&nbsp;'+lang('Edit Product');
                waitMessage = lang("Updating...");
            }else{
                requesturl = 'index.php?fuse=admin&action=Admin_AddProduct';
                buttonText = lang('Save');
                titleText = '&nbsp;&nbsp;'+lang('Add Product');
                waitMessage = lang("Adding...");


            }

                // create the form controls
                // have to recreate form controls
                //  each time the window is shown
                // due to bug in htmleditor
                //debugger;
                createUI();

                // create the window on the first click and reuse on subsequent clicks
                //debugger;
                win = new Ext.Window({
                    id: "myWin",
                    layout:'fit',
                    title:titleText,
                    width:windowWidth,
                    height:windowHeight,
                    plain: true,
                    modal:true,
                    closeAction:'close',
                    closable: true, /* removed close button due to documented bug in Ext.form.Combobox v3.0 in which it fires the change event when any window event occurs including close. I attempted to catch window event first and set flag but combobox change is the first event that gets fired somehow?*/
                    forceLayout:true, /*forces controls to render before form is displayed*/
                    defaults:{bodyStyle:'padding:0px;background-color:#F5F5F5 '},
                    items: [frmPackage],
                    listeners: {
                        hide: function() { frmPackage.destroy(); }
                    },
                    buttons:
                    [

                        {
                            text: 'Close',
                            handler: function()
                            {                              
                               win.close();
                            }
                        },
                        {
                            id: 'deleteButton',
                            text: 'Delete',
                            hidden: !update,
                            onClick: function(record)
                            {

                                requesturl = "index.php?fuse=admin&action=Admin_DeleteProduct"
                                Ext.Msg.show
                                (
                                    {
                                        title : "Delete?" ,
                                        msg: "Are you sure you want to delete this product?",
                                        buttons: Ext.Msg.YESNOCANCEL,
                                        fn: function(btn, text)
                                        {
                                            if (btn == 'yes')
                                            {
                                                deleteProduct(requesturl);
                                            }
                                        },
                                        icon: Ext.MessageBox.QUESTION

                                    }
                               );


                            }
                       },
                       {
                            text: buttonText,
                            handler: function (){

                                saveUpdateProduct(buttonText,requesturl,waitMessage);
                            }


                        }
                    ]
                });

              win.on('beforeclose',function(){
                //console.log('closing');
                closing=true;

              });

             if (!update){
                
                frmPackage.getForm().reset();
                setDefaultsForAdd();
                loadAddonsCombo();
                win.show();
             }

        }

        function createGeneralSettingsTabUI(){

            // billing cycles panels settings
            var billingCyclePanelsBorder = false;

            txtBillingCyclesMonthlyAmount = new Ext.form.NumberField({

                        xtype: "textfield",
                        name: "txtmonthlybilling",
                        width: 60,
                        x: 93,
                        y: 5,
                        value:"0.00",
                        validationEvent: false,
                        allowBlank: false

            });


            ckBillingCyclesMonthlyAmountAllowInSignup = new Ext.form.Checkbox({

                        xtype: "checkbox",
                        name: "ckBillingCyclesMonthlyAmountAllowInSignup",
                        width: 40,
                        fieldLabel: "Allow in signup",
                        x: 180,
                        y: 5,
                        checked: false

            });



            billingCyclesRowMonthlySignup = new Ext.Panel({

                layout: "absolute",
                name: "billingRowMonthlySignup",
                anchor: "100%",
                height: 35,
                border: billingCyclePanelsBorder,
                items: [
                      {
                        xtype: "label",
                        name: "lblmonthlybilling",
                        width: 80,
                        x: 5,
                        y: 14,
                        text: "Monthly",
                        style : "font-weight:bold"

                     },
                     txtBillingCyclesMonthlyAmount,
                     ckBillingCyclesMonthlyAmountAllowInSignup,

                    {
                        xtype: "label",
                        name: "lblckallowmonthlybillinginsignup",
                        width: 125,
                        x: 200,
                        y: 10,
                        text: "Allow in signup",
                        style : "font-weight:bold"

                     }
                ]

            });

            txtBillingCyclesQuarterlyAmount = new Ext.form.NumberField({

                        xtype: "textfield",
                        name: "txtmonthlybilling",
                        width: 60,
                        x: 93,
                        y: 5,
                        value:"0.00",
                        validationEvent: false,
                        allowBlank: false
            });


            ckBillingCyclesQuarterlyAmountAllowInSignup = new Ext.form.Checkbox({

                        xtype: "checkbox",
                        width: 40,
                        fieldLabel: "Allow in signup",
                        x: 180,
                        y: 5,
                        checked: false
                        
            });

            billingCyclesRowQuarterlySignup = new Ext.Panel({

                layout: "absolute",
                name: "billingRowMonthlySignup",
                anchor: "100%",
                height:35,
                y: 35,
                border: billingCyclePanelsBorder,
                items: [
                      {
                        xtype: "label",
                        name: "lblquarterlybilling",
                        width: 80,
                        x: 5,
                        y: 14,
                        text: "Quarterly",
                        style : "font-weight:bold"
                     },
                     txtBillingCyclesQuarterlyAmount,
                     ckBillingCyclesQuarterlyAmountAllowInSignup,
                    {
                        xtype: "label",
                        name: "lblckallowquarterlybillinginsignup",
                        width: 120,
                        x: 200,
                        y: 10,
                        text: "Allow in signup",
                        style : "font-weight:bold"
                     }
                ]

            });

            txtBillingCyclesSemiAnnualAmount = new Ext.form.NumberField({

                        xtype: "textfield",
                        width: 60,
                        x: 93,
                        y: 5,
                        value:"0.00",
                        validationEvent: false,
                        allowBlank: false
            });


            ckBillingCyclesSemiAnnualAmountAllowInSignup = new Ext.form.Checkbox({


                        xtype: "checkbox",
                        width: 40,
                        fieldLabel: "Allow in signup",
                        x: 180,
                        y: 5,
                        checked: false

            });

            billingCyclesRowSemiAnnualSignup = new Ext.Panel({

                layout: "absolute",
                name: "billingRowSemiAnnualSignup",
                anchor: "100%",
                height:35,
                y: 70,
                border: billingCyclePanelsBorder,
                items: [
                      {
                        xtype: "label",
                        name: "lblsemiannualbilling",
                        width: 80,
                        x: 5,
                        y: 14,
                        text: "Semi-Annual",
                        style : "font-weight:bold"

                     },
                      txtBillingCyclesSemiAnnualAmount,
                      ckBillingCyclesSemiAnnualAmountAllowInSignup,
                    {
                        xtype: "label",
                        name: "lblckallowsemiannualbillinginsignup",
                        width: 120,
                        x: 200,
                        y: 10,
                        text: "Allow in signup",
                        style : "font-weight:bold"

                     }
                ]

            });

            txtBillingCyclesAnnualAmount = new Ext.form.NumberField({

                        xtype: "textfield",
                        width: 60,
                        x: 93,
                        y: 5,
                        value:"0.00",
                        validationEvent: false,
                        allowBlank: false
            });


            ckBillingCyclesAnnualAmountAllowInSignup = new Ext.form.Checkbox({


                        xtype: "checkbox",
                        width: 40,
                        fieldLabel: "Allow in signup",
                        x: 180,
                        y: 5,
                        checked: false

            });

            billingCyclesRowAnnualSignup = new Ext.Panel({

                layout: "absolute",
                name: "billingRowAnnualSignup",
                anchor: "100%",
                height:35,
                y: 105,
                border: billingCyclePanelsBorder,
                items: [
                      {
                        xtype: "label",
                        name: "lblannualbilling",
                        width: 80,
                        x: 5,
                        y: 14,
                        text: "Annual",
                        style : "font-weight:bold"

                     },
                      txtBillingCyclesAnnualAmount,
                      ckBillingCyclesAnnualAmountAllowInSignup,
                    {
                        xtype: "label",
                        name: "lblckallowannualbillinginsignup",
                        width: 120,
                        x: 200,
                        y: 10,
                        text: "Allow in signup",
                        style : "font-weight:bold"

                     }
                ]

            });


            txtBillingCyclesBiennialAmount = new Ext.form.NumberField({

                        xtype: "textfield",
                        width: 60,
                        x: 93,
                        y: 5,
                        value:"0.00",
                        validationEvent: false,
                        allowBlank: false
            });


            ckBillingCyclesBiennialAmountAllowInSignup = new Ext.form.Checkbox({


                        xtype: "checkbox",
                        width: 40,
                        fieldLabel: "Allow in signup",
                        x: 180,
                        y: 5,
                        checked: false

            });

            billingCyclesRowBiennialSignup = new Ext.Panel({

                layout: "absolute",
                name: "billingRowBiAnnualSignup",
                anchor: "100%",
                height:35,
                y: 140,
                border: billingCyclePanelsBorder,
                items: [
                      {
                        xtype: "label",
                        width: 80,
                        x: 5,
                        y: 14,
                        text: "Two Years",
                        style : "font-weight:bold"

                     },
                      txtBillingCyclesBiennialAmount,
                      ckBillingCyclesBiennialAmountAllowInSignup,
                    {
                        xtype: "label",
                        width: 120,
                        x: 200,
                        y: 10,
                        text: "Allow in signup",
                        style : "font-weight:bold"

                     }
                ]

            });

            txtBillingCyclesSetupPrice = new Ext.form.NumberField({


                width: 60,
                x: 93,
                y: 5,
                value:"0.00",
                validationEvent: false,
                allowBlank: false
            });

            billingCyclesRowSetupPrice = new Ext.Panel({

                layout: "absolute",
                name: "billingRowSetupPrice",
                anchor: "100%",
                height:35,
                y: 175,
                border: billingCyclePanelsBorder,
                items: [
                      {
                        xtype: "label",
                        name: "lblsetupprice",
                        width: 80,
                        x: 5,
                        y: 14,
                        text: "Setup Price",
                        style : "font-weight:bold"

                     },
                     txtBillingCyclesSetupPrice
                ]

            });

            ckBillingCyclesPackageIsTaxable = new Ext.form.Checkbox({

                width: 10,
                x: 7,
                y: 10

            });

            billingCyclesRowPackageIsTaxable = new Ext.Panel({

                layout: "absolute",
                anchor: "100%",
                height: 35,
                y: 210,
                border: billingCyclePanelsBorder,
                items: [
                      {
                        xtype: "label",
                        name:  "lblallowinsignup",
                        width: 150,
                        x: 27,
                        y: 13,
                        text: "Product is Taxable?",
                        style : "font-weight:bold"

                     },
                     ckBillingCyclesPackageIsTaxable

                ]
            });

            billingCyclesPanel = new Ext.form.FieldSet({

                layout: "absolute",
                border:false,
                width: 257,
                height: 250,
                anchor: "100%",
                x: 0,
                style: 'padding:0px;background-color:#F5F5F5 ',
                items: [
                    {
                        layout: 'column',
                        border: false,
                        items:  [
                            {
                                columnWidth:  0.5,
                                layout:       'form',
                                border:       false,
                                items:        [
                                    billingCyclesRowMonthlySignup,
                                    billingCyclesRowQuarterlySignup,
                                    billingCyclesRowSemiAnnualSignup,
                                    billingCyclesRowAnnualSignup,
                                    billingCyclesRowBiennialSignup,
                                    billingCyclesRowSetupPrice,
                                    billingCyclesRowPackageIsTaxable
                                ]
                            },
                            {
                                columnWidth:  0.5,
                                layout:       'form',
                                border:       false,
                                items:        [
                                    {
                                        xtype:        'fieldset',
                                        id:           'addonsNotice',
                                        name:         'addonsNotice',
                                        title:        lang('NOTICE'),
                                        autoHeight:   true,
                                        defaults:     {width: 100},
                                        labelAlign:   'top',
                                        items :       [
                                            {
                                                xtype:          "label",
                                                id:             'BillingCyclesNotice',
                                                name:           'BillingCyclesNotice',
                                                fieldLabel:     lang('Addon prices for billing cycles not used in this product will not be available to the customer, unless you select the force show option in the addon setup screen.'),
                                                labelStyle:     "font-weight: bold;",
                                                labelSeparator: '',
                                                text:           "",
                                                style:          "font-weight: bold;"
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            });

            // general settings panel settings
            var generalSettingsPanelsBorder = false;
            var generalSettingsPanelsAnchor = "100%";
            var generalSettingsPanelsHeight = 35;
            var generalSettingsPanelsFirstRowTop = 5;


            txtGeneralSettingsPackageName = new Ext.form.TextField({

                        anchor: "100%",
                        x:100,
                        y:5,
                        validationEvent: false,
                        allowBlank: false
            });

            txtGeneralSettingsPackageName.on('blur',function(){

              setWindowTitle();

            });



            generalSettingsPackageName = new Ext.Panel({

                layout:"absolute",
                id: "generalSettingsPackageName",
                height: generalSettingsPanelsHeight,
                /*y: generalSettingsPanelsFirstRowTop,*/
                anchor: generalSettingsPanelsAnchor,
                border: generalSettingsPanelsBorder,
                style: "background-color:#F5F5F5",
                defaults : {bodyStyle: "background-color:#F5F5F5 "},
                items: [
                    {
                        xtype: "label",
                        x:5,
                        y:12,
                        width: 200,
                        text: 'Product Name',
                        name: 'lblPackageName',
                        style: "font-weight:bold; background-color:#F5F5F5 "
                    },
                    txtGeneralSettingsPackageName
                ]

            });

           productTypesStore = new Ext.data.JsonStore({

                root:           'productGroups', //'staff',
                totalProperty:  'totalcount',
                idProperty:     'id',
                remoteSort:     true,
                baseParams:     {
                                    groupsonly:1
                                },
                fields:         [
                                    'id',
                                    'name'
                                ],
                proxy:          new Ext.data.HttpProxy({
                                    url:  'index.php?fuse=admin&action=Admin_GetProductGroups&groupsonly'
                                })
            });

            productTypesStore.setDefaultSort('id', 'asc');

            productTypesStore.load();

            productTypesStore.on('load',function(){

                if (productType!=""){
                    cboGeneralSettingsPackageType.setValue(productType);
                    loadAddonsCombo();
                }

            });

            cboGeneralSettingsPackageType = new Ext.form.ComboBox({

                x: 100,
                y: 5,
                anchor: "100%",
                store: productTypesStore,
                typeAhead:        true,
                triggerAction:    'all',
                lazyRender:       true,
                mode:             'local',
                validationEvent:  false,
                valueField:       'id',
                displayField:     'name',
                hiddenId:         'productTypeId',
                hiddenName:       'productTypeName',
                allowBlank:       false,
                blankText:        lang("This field is required"),
                forceSelection:   true,
                editable:         false
            });

            cboGeneralSettingsPackageType.on('select',function (combo, record, index ){

                productType = cboGeneralSettingsPackageType.getValue();
                addonStore.removeAll();
                loadAddonsCombo();

            } );

            generalSettingsPackageType = new Ext.Panel({

                layout:"absolute",
                //height: 35,
                //y: 39,
                height: generalSettingsPanelsHeight,
               /*y: generalSettingsPanelsFirstRowTop,*/
                anchor: generalSettingsPanelsAnchor,
                border: generalSettingsPanelsBorder,
                items: [
                    {
                        xtype: "label",
                        x:5,
                        y:12,
                        width: 200,
                        text: lang('Product Group'),
                        name: 'lblPackageType',
                        style: "font-weight:bold"
                    },
                    cboGeneralSettingsPackageType
                  ]
            });

            lblGeneralSettingsSignupURL = new Ext.form.Label({
                id:     'signupurl',
                name:   'signupurl',
                anchor: "100%",
                x:      100,
                y:      5,
                style:  "font-weight:bold;border-width:5px;"
            });

            generalSettingsSignupURL = new Ext.Panel({

                layout: "absolute",
                height: generalSettingsPanelsHeight + 15,
                anchor: generalSettingsPanelsAnchor,
                border: generalSettingsPanelsBorder,
                hidden:true,
                items:  [
                    {
                        xtype:  "label",
                        text:   "Signup URL",
                        x:      5,
                        y:      5,
                        style:  "font-weight:bold"
                    },
                    lblGeneralSettingsSignupURL
                ]
             });


             ckGeneralSettingsShowPackageInSignup = new Ext.form.Checkbox({

                width: 10,
                x: 5,
                y: 5

             });
             generalSettingsShowPackageInSignup = new Ext.Panel({

                layout: "absolute",
                //y:73,
                //height: 35,
                height: generalSettingsPanelsHeight,
                y: generalSettingsPanelsFirstRowTop + (3 * generalSettingsPanelsHeight) - 3,
                anchor: generalSettingsPanelsAnchor,
                border: generalSettingsPanelsBorder,
                items : [
                            {
                                xtype: "label",
                                name:  "lblallowinsignup",
                                width: 150,
                                x: 25,
                                y: 10,
                                text: "Show in signup form?",
                                style : "font-weight:bold"
                            },ckGeneralSettingsShowPackageInSignup

                        ]

             });

             ckGeneralSettingsAllowDirectLink = new Ext.form.Checkbox({
                width: 10,
                x: 5,
                y: 5
             });

             ckGeneralSettingsAllowDirectLink.on('check',function(){


                 if (ckGeneralSettingsAllowDirectLink.checked && productId){

                    generalSettingsSignupURL.show();

                 }
                 else {

                    generalSettingsSignupURL.hide();
                 }
             });

             generalSettingsAllowDirectLink = new Ext.Panel({

                layout: "absolute",
                //y:73,
                //height: 35,
                height: generalSettingsPanelsHeight,
                y: generalSettingsPanelsFirstRowTop + (3 * generalSettingsPanelsHeight) - 3,
                anchor: generalSettingsPanelsAnchor,
                border: generalSettingsPanelsBorder,
                items : [
                    {
                        xtype: "label",
                        name:  "lblallowinsignup",
                        width: 150,
                        x: 25,
                        y: 10,
                        text: "Allow direct link?",
                        style : "font-weight:bold"
                    },ckGeneralSettingsAllowDirectLink

                ]

             });

           ckEmailSettingsUsePackageTypeWelcomeEmail = new Ext.form.Checkbox({
                id:               'usePackageTypeWelcomeEmail',
                name:             'usePackageTypeWelcomeEmail',
                value:            false,
                validationEvent:  false,
                hideLabel:        true,
                boxLabel :        "Use Product Group Default Welcome Email",
                style:            "font-weight: bold"
           });

           ckEmailSettingsUsePackageTypeWelcomeEmail.on('check',function(){

               if (ckEmailSettingsUsePackageTypeWelcomeEmail.checked){

                    txtEmailSettingsSubject.disable();                   
                    productWelcomeEmailTabs.disable();
                   
               }
               else {
                    
                    txtEmailSettingsSubject.enable();
                    productWelcomeEmailTabs.enable();

               }
           });

           ckEmailSettingsSendWelcomeEmail = new Ext.form.Checkbox({
                id:               'sendWelcomeEmail',
                name:             'sendWelcomeEmail',
                value:            false,
                validationEvent:  false,
                hideLabel:        true,
                boxLabel :        'Send Welcome E-mail when activating a new customer',
                style:            "font-weight: bold"
           });

           emailSettingsUsePackageTypeWelcomeEmail  = new Ext.Panel({
                layout: 'column',
                autoHeight:   true,
                anchor: generalSettingsPanelsAnchor,
                border: false,
                items : [
                            {
                                columnWidth:  .5,
                                layout:       'form',
                                border:       false,
                                items:        [
                                                  ckEmailSettingsUsePackageTypeWelcomeEmail
                                              ]
                            },
                            {
                                columnWidth:  .5,
                                layout:       'form',
                                border:       false,
                                items:        [
                                                  ckEmailSettingsSendWelcomeEmail
                                              ]
                            }
                        ]

            });

            txtEmailSettingsSubject = new Ext.form.TextField({
                x: 55,
                y: 8,
                anchor: "100%"
            });

            emailSettingsSubject = new Ext.Panel({

                layout: "absolute",
                height: 30,
                x: 5,
                y: 22,
                anchor: generalSettingsPanelsAnchor,
                border: false,
                items : [txtEmailSettingsSubject,
                           {
                                 xtype: "label",
                                 width: 50,
                                 x: 3, 
                                 y: 15,
                                 text: "Subject",
                                 style: "font-weight: bold"
                             }
                        ]
            });

            htmlEditProductDescription = new Ext.form.HtmlEditor({

                x: 5,
                y: 42,
                hideMode: 'offsets',
                listeners:
                    {
                        activate: function(e) {
                            e.execCmd('delete');
                        }
                    }

            });

            htmlEditProductWelcomeEmail = new Ext.form.HtmlEditor({

                x: 5,
                y: 42,
                hideMode: 'offsets',
                listeners: {
                        activate: function(e) {
                            e.execCmd('delete');
                        }
                    }

            });

            txtProductWelcomeEmail = new Ext.form.TextArea({
                x:5,
                y:5,
                height: 195,
                anchor: "90%"
            });

            productWelcomeEmailTabs = new Ext.TabPanel({

                activeTab: 0,
                height: 225,
                x: 5,
                y: 57,
                anchor: '100%',
                autoScrollTabs: true,
                deferredRender : false,
                layoutOnTabChange: true,
                defaults:{bodyStyle:'padding:5px'},
                items: [
                    {
                        id: "tabPageProductHtmlWelcomeEmail",
                        name: "tabPageProductHtmlWelcomeEmail",
                        cls:'x-plain',
                        title:'HTML',
                        layout: "fit",
                        items: [htmlEditProductWelcomeEmail]
                    },
                    {
                        id: "tabPageProductTxtWelcomeEmail",
                        name: "tabPageProductTxtWelcomeEmail",
                        cls:'x-plain',
                        title:'Text',
                        layout: "fit",
                        items: [txtProductWelcomeEmail]
                    }

                ]
            });


            productTabs = new Ext.TabPanel(
            {
                    plain:true,
                    activeTab: 0,
                    /* important - if height is too tall then
                     * "package description" htmleditor expands upward
                     * (pushing controls that are above the tabs up and out of view)
                     * when "source edit" button is clicked on htmleditor toolbar in IE 7*/
                    height: 350,
                    anchor: "100%",
                    autoScrollTabs: true,
                    deferredRender: false,
                    layoutOnTabChange: true,
                    /*style: "padding: 10px; margin: 5px",*/
                    defaults:{bodyStyle:'padding:5px'},
                    items:[{
                        cls:'x-plain',
                        title:'Billing Cycles',
                        layout: "form",
                        items: [
                            billingCyclesPanel

                        ]
                    },{
                        cls:'x-plain',
                        title:'Product Description',
                        layout: "fit",
                        items: [htmlEditProductDescription]
                    },{
                        cls:'x-plain',
                        name: "tabPageWecomeEmail",
                        title:'Welcome Email',
                        layout: "absolute",
                        items: [
                                    emailSettingsUsePackageTypeWelcomeEmail,
                                    emailSettingsSubject,
                                    productWelcomeEmailTabs
                                ]
                    }]

            });


                tabPagePackageGeneral = new Ext.Panel({
                labelAlign: 'top',
                plain: true,
                anchor: '100%',
                defaults:   {bodyStyle:'padding:5px; background-color:#F5F5F5'},
                items: [
                    /*generalSettingsPanel*/
                    {
                    layout:'column',
                    border:false,
                    items:[{
                        columnWidth:.5,
                        layout: 'form',
                        border:false,
                        style:'padding:5px;background-color:#F5F5F5 ',
                        items: [generalSettingsPackageName,
                                generalSettingsAllowDirectLink
                                ]
                    },
                    {
                        columnWidth:.5,
                        style:'padding:5px;background-color:#F5F5F5 ',
                        layout: 'form',
                        border:false,
                        items: [
                            generalSettingsPackageType,
                            generalSettingsShowPackageInSignup
                        ]
                    },
                    {
                        columnWidth: 1,
                        style:'padding:5px;background-color:#F5F5F5 ',
                        layout: 'form',
                        border:false,
                        items: [
                            generalSettingsSignupURL
                        ]
                    }
                    ]
                },
                productTabs
                ]
            });

        }

        // addon tabs
        function createAdvanceTabUI() {


             hostManagerPluginTable = {

                    id: 'tabel-panel',
                    anchor: "97%,100%",
                    autoScroll: true,
                    cls: 'x-props-grid'

            };
            saveTextFieldValue = function(respObjKey,fieldArray,fieldId){

                //debugger;
                var value = $(fieldId).value;
                respObj = pluginCollection.get(respObjKey);

                if (fieldArray==""){
                    respObj.inputValue = value;
                }
                else if (fieldArray=="package_vars"){

                    for (i=0;i<respObj.package_vars.length;i++){

                        if (fieldId==respObj.package_vars[i].id){

                            respObj.package_vars[i].packageAttrFieldValue = value;
                            break;
                        }
                    }
                }
                else if (fieldArray=="aclResourceLimitsfields"){

                    for (i=0;i<respObj.reseller_acl_fields.aclResourceLimitsfields.length;i++){

                        if (fieldId==respObj.reseller_acl_fields.aclResourceLimitsfields[i].id){

                            respObj.reseller_acl_fields.aclResourceLimitsfields[i].aclValue = value;
                            break;
                        }
                    }

                }


            }
            saveCheckFieldValue = function(respObjKey,fieldArray,fieldId){

                
                var checked = ($(fieldId).checked)?1:0;
                respObj = pluginCollection.get(respObjKey);

                if (fieldArray=="package_vars"){

                    for (i=0;i<respObj.package_vars.length;i++){

                        if (fieldId==respObj.package_vars[i].id){

                            respObj.package_vars[i].packageAttrChecked = checked;
                            break;
                        }
                    }
                }
                else if (fieldArray=="aclResourceLimitsfields"){

                    for (i=0;i<respObj.reseller_acl_fields.aclResourceLimitsfields.length;i++){

                        if (fieldId==respObj.reseller_acl_fields.aclResourceLimitsfields[i].id){

                            respObj.reseller_acl_fields.aclResourceLimitsfields[i].aclChecked = checked;
                            break;
                        }
                    }

                }else if (fieldArray=="aclNonResourceLimitsfields") {

                    for (i=0;i<respObj.reseller_acl_fields.aclNonResourceLimitsfields.length;i++){

                        if (fieldId==respObj.reseller_acl_fields.aclNonResourceLimitsfields[i].id){

                            respObj.reseller_acl_fields.aclNonResourceLimitsfields[i].aclOptionChecked = checked;
                            break;
                        }
                    }
                }
            }

            loadPluginFields = function(respObj){

                if (!Ext.getCmp('tabel-panel') || !Ext.getCmp('tabel-panel').body ) {
                    myMask.hide();
                    return;
                }

                //debugger;
                var i = 0;
                var theValue;
                var valEvent;
                var pluginInternalName = respObj.pluginInternalName;

                // package variables
                var pkgVarDesc;
                var pkgVarInputType;
                var pkgVarId;
                var pkgVarChecked;
                var pkgVarValue;


                // acl variables
                var tblOpen = '<table class="x-grid3-row-table" cellspacing="0" cellpadding="0" width="100%" style="table-layout:fixed;" ><tbody><col width="75%"><col width="25%">';
                var tblClose = '</tbody></table>';
                var td0 = '<td class="x-grid3-col x-grid3-cell x-grid3-td-name x-grid3-cell-first" style="border-bottom: thin inset;-moz-user-select: text!important;-html-user-select: text!important;" >';
                var div0Open = '<div class="x-grid3-cell-inner x-grid3-col-name" style="white-space:normal !important;" >';
                var div1Open = '<div class="x-grid3-cell-inner x-grid3-col-value" >';
                var divClose = '</div>';
                var td1 = '<td class="x-grid3-col x-grid3-cell x-grid3-td-value x-grid3-cell-last " style="text-align: center;border-bottom: thin inset;-moz-user-select: text!important;-html-user-select: text!important;">';
                var aclType;
                var aclDesc;
                var aclValue;
                var aclChecked;
                var aclName;
                var aclId;
                //var s = '<div class=" x-panel x-grid-panel" style="width: 300px;">';
                var s = '<div class="x-grid3" hidefocus="true"><div class="x-grid3-viewport" >';
                s += '<div class="x-panel-bwrap" >';
                s += '<div class="x-grid3-body" >';


                if (respObj.pluginInputVarDisabled==0){

                    valEvent = 'onBlur=saveTextFieldValue("'+pluginInternalName+'",'+'""'+',"'+respObj.inputName+'")';
                    s += tblOpen;
                    s += '<tr>' + td0 + div0Open + 'Alternate Name' + divClose + '</td>';
                    s += td1 + div1Open + '<input type="text" id="' + respObj.inputName + '" value="' + respObj.inputValue + '" ' + valEvent + '>' + divClose + '</td></tr>';
                    s += tblClose;

                }

                if (respObj.package_vars) {


                    for(var i=0;i<respObj.package_vars.length;i++){

                        pkgVarDesc = respObj.package_vars[i].packageAttrDescription;
                        pkgVarInputType = respObj.package_vars[i].packageAttrInputType;
                        pkgVarId = respObj.package_vars[i].id;
                        pkgVarChecked = respObj.package_vars[i].packageAttrChecked;
                        pkgVarValue = respObj.package_vars[i].packageAttrFieldValue;


                        if (pkgVarInputType=="text"){
                            theValue = 'value="' + (pkgVarValue || '') + '"';
                            valEvent = 'onBlur=saveTextFieldValue("'+pluginInternalName+'",'+'"package_vars"'+',"'+pkgVarId+'")';

                        }
                        else if (pkgVarInputType=="checkbox"){

                            theValue = (pkgVarChecked==1)? "checked": "";
                            valEvent = 'onClick=saveCheckFieldValue("'+pluginInternalName+'",'+'"package_vars"'+',"'+pkgVarId+'")';
                        }

                        s += tblOpen;
                        s += '<tr>' + td0 + div0Open +  Ext.util.Format.htmlDecode(pkgVarDesc) + divClose +  '</td>';
                        s += td1 + div1Open +  '<input type="' + pkgVarInputType + '" id="' + pkgVarId + '" ' + theValue + ' ' + valEvent + ' >' + divClose +  '</td></tr>';
                        s += tblClose;
                    }
                }
                else if (respObj.reseller_acl_fields) {


                    //Resource Usage:
                     s += tblOpen;
                     s += '<tr><td style="font-weight:bold" >Resource Usage:</td>';
                     s += '<td style="text-align: center;">&nbsp;</td></tr>';
                     s += tblClose;

                    for(i =0;i<respObj.reseller_acl_fields.aclResourceLimitsfields.length;i++){

                        aclType = respObj.reseller_acl_fields.aclResourceLimitsfields[i].aclType;
                        aclDesc = respObj.reseller_acl_fields.aclResourceLimitsfields[i].aclDesc;
                        aclValue = respObj.reseller_acl_fields.aclResourceLimitsfields[i].aclValue;
                        aclChecked = respObj.reseller_acl_fields.aclResourceLimitsfields[i].aclChecked;
                        aclName = respObj.reseller_acl_fields.aclResourceLimitsfields[i].aclName;
                        aclId = respObj.reseller_acl_fields.aclResourceLimitsfields[i].id;


                        if (aclType=="text"){
                            theValue = 'value="' + (aclValue || '') + '"';
                            valEvent = 'onBlur=saveTextFieldValue("'+pluginInternalName+'",'+'"aclResourceLimitsfields"'+',"'+aclId+'")';
                        }
                        else if (aclType=="checkbox"){

                            theValue = (aclChecked==1)? "checked": "";
                            valEvent = 'onClick=saveCheckFieldValue("'+pluginInternalName+'",'+'"aclResourceLimitsfields"'+',"'+aclId+'")';
                        }

                        s += tblOpen;
                        s += '<tr>' + td0 + div0Open +  Ext.util.Format.htmlDecode(aclDesc) + divClose +  '</td>';
                        s += td1 + div1Open + '<input type="' + aclType + '" id="' + aclId + '" ' + theValue + ' ' + valEvent + ' >' + divClose + '</td></tr>';
                        s += tblClose;

                    }

                    //ACL Options:
                    s += tblOpen;
                    s += '<tr><td style="font-weight:bold" >ACL Options:</td>';
                    s += '<td style="text-align: center;">&nbsp;</td></tr>';
                    s += tblClose;
                    for(i =0;i<respObj.reseller_acl_fields.aclNonResourceLimitsfields.length;i++){


                        aclDesc = respObj.reseller_acl_fields.aclNonResourceLimitsfields[i].aclDesc;
                        aclChecked = respObj.reseller_acl_fields.aclNonResourceLimitsfields[i].aclOptionChecked;
                        aclName = respObj.reseller_acl_fields.aclNonResourceLimitsfields[i].aclName;
                        aclId = respObj.reseller_acl_fields.aclNonResourceLimitsfields[i].id;


                        theValue = (aclChecked==1)? "checked": "";
                        valEvent = 'onClick=saveCheckFieldValue("'+pluginInternalName+'",'+'"aclNonResourceLimitsfields"'+',"'+aclId+'")';

                        s += tblOpen;
                        s += '<tr>' + td0 + div0Open +  Ext.util.Format.htmlDecode(aclDesc) + divClose + '</td>';
                        s += td1 + div1Open + '<input type="checkbox" id="' + aclId + '" ' + theValue + ' ' + valEvent + ' >' + divClose + '</td></tr>';
                        s += tblClose;

                    }

                }
               
                s += '</div></div></div></div>';

                try{
                    Ext.getCmp('tabel-panel').body.update(s);
                    Ext.getCmp('tabel-panel').doLayout();
                    Ext.getCmp('tabel-panel').autoScroll = true;
                }catch(e){}
                myMask.hide();

            }

            onPluginReceived = function(requestObject) {

                //debugger;
                var respObj = eval('(' + requestObject.responseText + ')');

                //pluginStore = respObj;

                if (!pluginCollection.exists(respObj.pluginInternalName)){
                    pluginCollection.add(respObj.pluginInternalName,respObj)
                }

                loadPluginFields(respObj);

            }


            serverStore = new Ext.data.JsonStore({

                root:           'servers', //'departments',
                totalProperty:  'totalcount',
                idProperty:     'serverid',
                remoteSort:     true,
                baseParams:     {
                                    filter: "",
                                    customerid: "0"
                                },
                fields:         [
                                    'serverid',
                                    'servername',
                                    'hostname',
                                    'ip',
                                    'isdefault',
                                    'plugin',
                                    'servernameandplugin'
                                ],
                proxy:          new Ext.data.HttpProxy({
                                    url:  'index.php?fuse=admin&action=Admin_GetServers'
                                })
            });

            serverStore.setDefaultSort('id', 'asc');

            serverStore.load();




            lovComboProductServers = new Ext.ux.form.LovCombo({
                id:'lovComboProductServers'
                ,beforeBlur : Ext.emptyFn
		,anchor: "100%"
		,hideOnSelect:false
		,maxHeight:200
		,store: serverStore
                ,hideLabel: true
                ,triggerAction:    'all'
                ,lazyRender:       false
                ,mode:             'local'
                ,validationEvent:  false
                ,valueField:       'serverid'
                ,displayField:     'servernameandplugin'

            });

           

            lovComboProductServers.on('change',function(){
                 //Ext.MessageBox.alert('lovcombochange','change');                
                 synchServerCombos(okForServerPluginAlert);
                 //getHostManagerPluginFields();

            });

            serverStore.on('load',function(){

                if (serverIds!=""){

                    lovComboProductServers.setValue(serverIds)

                }
            });

            MyCustomRecord = Ext.data.Record.create(['serverid','servername','hostmanagername']);
            hostManagerStore = new Ext.data.JsonStore({
                root:           'servers', //'departments',
                totalProperty:  'totalcount',
                idProperty:     'serverid',
                remoteSort:     true,
                baseParams:     {
                                    filter: "",
                                    customerid: "0"
                                },
                fields:         [
                                    'serverid',
                                    'servername'
                                ],
                proxy:          new Ext.data.HttpProxy({
                                    url:  'index.php?fuse=admin&action=Admin_GetServers'
                                })

            });

            hostManagerStore.setDefaultSort('id', 'asc');
            hostManagerStore.load();

            hostManagerStore.on('load',function(){

                 hostManagerStore.removeAll();

                 if (update){
                    try{
                     synchServerCombos(true);
                    }catch(e){}
                 }

            });

            cboSelectServerHostManager = new Ext.form.ComboBox({

                id: "whatever",
                name: "whatever",
                store: hostManagerStore,
                lazyRender: false,
                displayField: "hostingmanagername",
                valueField: "serverid",
                triggerAction: "all",
                width: defaultWidth,
                anchor: "50%",

                editable: false,
                hideLabel: true

            });

            //captureEvents(cboSelectServerHostManager);


            cboSelectServerHostManager.on('selectionchange',function(selectionmodel){
                //debugger;
                synchServerCombos(true);
                getHostManagerPluginFields();

            });

            function getHostManagerOptions(hostingmanagername){

                if (!pluginCollection.exists(hostingmanagername)) {
                    //debugger;
                     myMask.show();
                     if (Ext.getCmp('tabel-panel') && Ext.getCmp('tabel-panel').body){

                         Ext.getCmp('tabel-panel').body.update('');
                         Ext.getCmp('tabel-panel').doLayout();
                     }
                     new Ajax.Request('index.php?fuse=admin&action=Admin_GetProductServerPluginOptions&pluginname=' + hostingmanagername + '&packageid=' + productId,
                        {
                            onComplete: onPluginReceived
                        }
                      );
                }
                else {
                    //debugger;
                    loadPluginFields(pluginCollection.get(hostingmanagername));
                }

            }

            cboSelectServerHostManager.on('select',function(){

            getHostManagerPluginFields();




            });

        getHostManagerPluginFields = function(){

                //myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});

                var header = Ext.getCmp('hostingmanageroptionsheader');

                header.setTitle("Hosting Manager options - " + cboSelectServerHostManager.lastSelectionText);

                var northregion = Ext.getCmp('productservergridregion');


                //debugger;
                var theId = cboSelectServerHostManager.getValue();

                var d = hostManagerStore.data;

                for(var i=0; i<d.length;i++){

                    if (theId==d.items[i].data.serverid){

                        getHostManagerOptions(d.items[i].data.hostingmanagername)
                        break;
                    }

                }

        }
           
            lovComboProductServers.on('collapse',function(){

                okForServerPluginAlert =true

            });

            synchServerCombos = function(okForSrvPluginAlert) {
                okForServerPluginAlert = false; // work around for documented combobox bug in which change event fires when window clicked, moved, closed
                var s = lovComboProductServers.getCheckedValue();
                
                if (s == "") {
                    // clear hosting manager combo
                    cboSelectServerHostManager.setValue("");
                    hostManagerStore.removeAll();
                    // clear hosting manager fields
                    if (Ext.getCmp('tabel-panel') && Ext.getCmp('tabel-panel').body){

                         Ext.getCmp('tabel-panel').body.update('');
                         Ext.getCmp('tabel-panel').doLayout();
                     }
                    return;
                }
                
                var servers = s.split(',');
                
                hostManagerStore.removeAll();
                hostManagerStore.totalLength = 0;
                if (Ext.getCmp('tabel-panel') && Ext.getCmp('tabel-panel').body){

                    Ext.getCmp('tabel-panel').body.update('');
                }
                //propertyGridHostManagerPluginSettings.setSource("");
                //pluginStore = null;
                cboSelectServerHostManager.setValue("");
                var header = Ext.getCmp('hostingmanageroptionsheader');
                header.setTitle("Hosting Manager options");

                var aserverid=0;
                var selectedServersWithNoPlugin = "";

                for(var i = 0; i < servers.length; i++){
                    for(var j = 0; j < serverStore.data.length; j++){

                        if (servers[i] == serverStore.data.items[j].data.serverid){
                            aserverid = serverStore.data.items[j].data.serverid;
                            //var aservername = serverStore.data.items[j].data.servername + ' - ' + serverStore.data.items[j].data.plugin;
                            var aservername = serverStore.data.items[j].data.servername;
                            var aserverplugin = serverStore.data.items[j].data.plugin;

                            var found = false;
                            //debugger;

                            for(var x = 0; x < hostManagerStore.data.length; x++){

                                if (aserverplugin == hostManagerStore.data.items[x].data.hostingmanagername){
                                    found = true;
                                    break;
                                }
                            }
                            
                            
                            if (!found && aserverplugin != ""){
                                var rec = new MyCustomRecord({"serverid":aserverid,"servername":aservername,"hostingmanagername":aserverplugin});
                                hostManagerStore.add(rec);
                            }else if (aserverplugin == "") {
                                if (selectedServersWithNoPlugin==""){
                                    selectedServersWithNoPlugin += aservername;
                                }
                                else {
                                    selectedServersWithNoPlugin += "<br>" + aservername;
                                }
                            }
                        }
                    }
                }

                if (selectedServersWithNoPlugin.length>0){
                    if (okForSrvPluginAlert){
                        Ext.MessageBox.alert("Server Plugin Not Configured","The following selected servers do not have a plugin configured: <br>" + selectedServersWithNoPlugin + "<br>You can add a plugin to this server(s) in the Servers\\Domains admin screen.")
                    }
                }

                if (hostManagerStore.data.length>0 && Ext.getCmp('tabel-panel')!==null){

                    var serverid = hostManagerStore.data.items[0].data.serverid;
                    cboSelectServerHostManager.setValue(serverid);
                    getHostManagerOptions(hostManagerStore.data.items[0].data.hostingmanagername)
                }



            };


            serversMultiSelectPanel = new Ext.Panel({
                id: "serversMultiSelectPanel",
                layout: "column",
                /*height: 180,*/
                style: "border-style:none",
                border: false,
                defaults: {
                  border: false },

                items : [{
                          columnWidth:.00,
                          border: false,
                          html: "&nbsp;"
                          },
                          {
                          columnWidth:.50,
                          style: "border-style:none",
                          layout: "form",
                          items :[lovComboProductServers]
                          },
                          {
                          columnWidth:.50,
                          border: false,
                          html: "&nbsp;"
                          }
                        ]

            });

            serversNoticePanel = new Ext.Panel({
                id: "serversNoticePanel",
                height: 450,
                anchor: "100%,100%",
                border: false,
                layout: "vbox",
                layoutConfig: {
                    align : 'stretch',
                    pack  : 'start',
                    autoScroll: true
                },
                defaults: {
                    border: false,
                    collapsible: true,
                    autoScroll: true,
                    split: true,
                    autoHide: false,
                    useSplitTips: true,
                    bodyStyle: 'padding:5px'
                },
                items: [{
                            id: "productservergridregion",
                            region: "north",
                            title: "Servers associated with this product",
                            height: 70,
                            margins: '5 0 0 0',
                            collapsible: false,
                            items: [ serversMultiSelectPanel]
                        },
                        {
                            id : "cboHostingManagerOptions",
                            title: "Server Plugin Options",
                            collapsible: false,
                            height: 70,
                            layout: "form",
                            items: [cboSelectServerHostManager]
                        },
                        {
                            id: "hostingmanageroptionsheader",
                            region: "center",
                            collapsible: false,
                            layout: "form",
                            height: 280,
                            floatable: true,
                            /*cmargins: '5 0 0 0',*/
                            autoScroll:true,
                            /*defaults: {border: false},*/
                            items:[hostManagerPluginTable]
                            /*items: [propertyGridHostManagerPluginSettings]*/
                        }
                    ]
            });

            tabPageAdvanced = new Ext.Panel({
               id: "tabPageServers",
               layout: "anchor",
               anchor: "100%",
               items : [serversNoticePanel]
            });

        };

        // addons
        function createAddonUI(){            

           //  Json Store has built-in JsonReader
            addonLovComboStore = new Ext.data.JsonStore({
                fields: [{name: 'id'}, {name: 'name'},{name: 'description'},{name: 'plugin_var'},{name: 'order',type:'int'},{name: 'taxable',type:'bool'}],
                root:           'addons',
                totalProperty:  'totalcount',
                idProperty:     'id',
                /*baseParams: {productgroup_id: productGroupId},*/
                sortInfo: {field: "order", direction: "ASC"},                
                url: "index.php?fuse=admin&action=Admin_GetAddons",
                /*baseParams: {product_group_id:cboGeneralSettingsPackageType.getVlaue()},*/
                listeners: {
                    load: function(store,records,options){
                        //if (!Ext.isIE) console.log(records);

                    }
                }

            });
          

              lovComboAddons = new Ext.form.ComboBox({ //new Ext.ux.form.LovCombo({
                id:'lovComboAddons'
                ,beforeBlur : Ext.emptyFn
		/*,anchor: "85%"*/
                ,width: 200
                ,x: 70
                ,y: 2
		,hideOnSelect:false
                ,fieldLabel: "Select Addons:"
		,maxHeight:200
		,store: addonLovComboStore
                ,tpl: '<tpl for="."><div ext:qtip="<b>Name</b>: {name}<br/><b>Description</b>: {description}<br/>" class="x-combo-list-item">{name}</div></tpl>'
                ,triggerAction:    'all'
                ,lazyRender:       false
                ,mode:             'local'
                ,validationEvent:  false
                ,valueField:       'id'
                ,displayField:     'name',
                listeners: {
                    change: function(lovCombo, newValue, oldValue){


                    },
                    select : function( combo, record, index ) {

                        var row = record.data;

                        if (row.checked) {
                            var temp = new addon({
                            id: row.id,
                            name: row.name,
                            description: row.description,
                            plugin_var: row.plugin_var,
                            order: row.order,
                            taxable: row.taxable

                            });

                            addonStore.insert(addonStore.getCount(), temp);
                        }
                        else {

                            for(var i=0;i<addonStore.data.length;i++){
                                var thisRow = addonStore.data.items[i].data;
                                if (row.id == thisRow.id){

                                    addonStore.remove(addonStore.data.items[i]);
                                }
                            }
                        }
                        addonGrid.getView().refresh(true);

                    }
                }

            });

            addonStyleStore = new Ext.data.ArrayStore({
              idIndex:  0,
              fields:   [
                            'style',
                            'stylename'
                        ],
              data:     [
                            [
                                0,
                                lang("Drop-down menus")
                            ],
                            [
                                1,
                                lang("Radio buttons")
                            ]
                        ]
            });

            cboProductAddonStyle = new Ext.form.ComboBox({

                anchor: "90%",
                height: 20,
                xtype: "combo",
                lazyRender: false,
                validationEvent:  false,
                triggerAction: "all",
                mode: 'local',
                fieldLabel: "Addon Display Style",
                store:    addonStyleStore,
                valueField:       'style',
                displayField:     'stylename',
                value:            0,
                hiddenId:         'style',
                hiddenName:       'stylename',
                forceSelection:   true,
                editable:         false


            });

            addon = Ext.data.Record.create([
            {
                name: 'id',
                type: 'int'
            },
            {
                name: 'package_id',
                type: 'int'
            },
            {
                name: 'name',
                type: 'string'
            },
            {
                name: 'description',
                type: 'string'
            },
            {
                name: 'plugin_var',
                type: 'string'
            },
            {
                name: 'order',
                type: 'int'
            },
            {
                name: 'taxable',
                type: 'int'
            }
            ]);

            function renderYesNo(value,p,record){
                if (value == 1) return lang("Yes");
                return lang("No");
            }


            // Json Store has built-in JsonReader
            addonStore = new Ext.data.JsonStore({
                fields: [{name: 'id'}, {name: 'package_id'},{name: 'name'},{name: 'description'},{name: 'plugin_var'},{name: 'order',type:'int'},{name: 'taxable',type:'bool'}],
                root:           'addons',
                totalProperty:  'totalcount',
                idProperty:     'id',
                baseParams: {packageid: productId},
                sortInfo: {field: "order", direction: "ASC"},
                /*url: 'index.php?fuse=admin&action=Admin_GetProductAddons',*/
                /*url: addonUrl,*/
                baseParams: {packageid:productId},
                listeners: {
                    load: function(store,records,options){
                        if (!Ext.isIE) console.log(records);
                    }
                }

            });

            //addonStore.load();

           
//            function italic(value){
//                return '<i>' + value + '</i>';
//            }

            // example of custom renderer function
//            function change(val){
//                if(val > 0){
//                    return '<span style="color:green;">' + val + '</span>';
//                }else if(val < 0){
//                    return '<span style="color:red;">' + val + '</span>';
//                }
//                return val;
//            }
            // example of custom renderer function
//            function pctChange(val){
//                if(val > 0){
//                    return '<span style="color:green;">' + val + '%</span>';
//                }else if(val < 0){
//                    return '<span style="color:red;">' + val + '%</span>';
//                }
//                return val;
//            }

            // render rating as "A", "B" or "C" depending upon numeric value.
//            function rating(v) {
//                if (v === 0) { return "A";}
//                if (v === 1) { return "B";}
//                if (v === 2) { return "C";}
//            }




//            addonRowSelectionModel = new Ext.grid.RowSelectionModel({
//                    singleSelect: false
//
//             });



            addonGridView = new Ext.grid.GridView({

                forceFit: true

            });


            S4 = function() {
                return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
            }



            function btnAddonEdit_Click(grid,record,action,value){

                btnAddonPricesSaveUpdate.setText('update');
                Ext.getCmp('txtaddonname').setValue(record.data.name);
                Ext.getCmp('txtaddondescription').setValue(record.data.description);
                Ext.getCmp('ckaddontaxable').setValue(record.data.taxable);
                Ext.getCmp('cbopluginvar').setValue(record.data.plugin_var);

                Ext.getCmp('productaddonsbordercenter').collapse();

                addonLoadPrices(productId,record.data.id)


            }

            function btnAddonDelete_Click(grid,record,action,value){

                moveAddonFromGridToCombo(record);

            }

            addonGridCellActions = new Ext.ux.grid.CellActions({
                listeners:{
                        action:function(grid, record, action, value) {


                            if (action=="icon-edit"){

                                btnAddonEdit_Click(grid,record,action,value);



                            }else if (action=="icon-delete"){

                                btnAddonDelete_Click(grid,record,action,value);


                            }
                            
                        }
                        ,beforeaction:function() {
                                
                        }
                }
                ,callbacks:{
//                        'icon-undo':function(grid, record, action, value) {
//                                Ext.msg('Callback: icon-undo', 'You have clicked: <b>{0}</b>, action: <b>{1}</b>', value, action);
//                        }
                }
                ,align:'left'
            });


            addonGrid = new Ext.grid.GridPanel({
                
                ds: addonStore,               
                defaults: {
                    sortable: true
                },
                columns:
                    [                        
                        {id: 'id', width:10, header: 'Id', hidden:true, sortable: true, dataIndex: 'id'

                        },
                        {header:'Name', width: 100,hidden:false, sortable: true, locked:false, dataIndex: 'name',
                        cellActions:[
                                       /*{
                                        iconCls:'icon-edit'
                                        ,qtip:'Click to Edit'
                                        ,hide:true
                                        ,hideMode:'display'
                                        },*/
                                        {
                                         iconCls:'icon-delete'
                                         ,qtip:'Click to Delete'
                                        }
                                    ]
                        },
                        {header: "Description", hidden:false, width: 100, sortable: true,locked:false,  dataIndex: 'description'},
                        {header: "Plugin", width: 55, sortable: true, dataIndex: 'plugin_var'},
                        {header: "Taxable", width: 60, sortable: true, dataIndex: 'taxable',renderer: renderYesNo}

                    ]
                ,
                enableDragDrop    : true,
                ddGroup     : 'myGridDD',
                dragConfig : {
                    containerScroll : true

                },
                stripeRows: true,
                listeners: {

                    rowdblclick: function(grid,rowIndex,event){
                        //btnAddonEdit_Click(null,addonStore.data.items[rowIndex],null,null);
                    },
                    render: function(){
                          
                           Ext.Ajax.request({
                            url: 'index.php?fuse=admin&action=Admin_GetProductAddons',
                            params: {
                                product_id: productId
                            },
                            success: function(respObj){
                                if (respObj.status==200){

                                   var data = Ext.util.JSON.decode(respObj.responseText);
                                   if (data){

                                        var addonids = "";
                                        for(var i=0;i<data.addon.length;i++){
                                            var row = data.addon[i];

                                            if (i<data.addon.length-1) {
                                                addonids += row.id + ",";
                                            }
                                            else {
                                                addonids += row.id
                                            }

                                            var temp = new addon({
                                            id: row.id,
                                            name: row.name,
                                            description: row.description,
                                            plugin_var: row.plugin_var,
                                            order: row.order,
                                            taxable: row.taxable

                                            });

                                            // remove item from combo
                                            for(var x=0;x<addonLovComboStore.data.length;x++){
                                                var lovItem = addonLovComboStore.data.items[x];
                                                var lovRow = lovItem.data;
                                                if (lovRow.id==row.id){

                                                    addonLovComboStore.remove(lovItem);
                                                    lovComboAddons.setValue('');
                                                }

                                            }

                                            addonStore.insert(addonStore.getCount(), temp);

                                        }
                                        //lovComboAddons.setValue(addonids);
                                        addonStore.commitChanges();
                                        addonGrid.getView().refresh(true);
                                        addonsRendered = true;

                                   }
                                }
                            }

                        });

                    }
                },
                plugins:[addonGridCellActions],              
                view: addonGridView,
                autoExpandColumn: 'name',
                height: 250,
                title:'',
                border: true                

            });

           var dropTargetCfg = {

            ddGroup         : 'myGridDD',
            onContainerOver : function(ddSrc, evtObj, ddData) {
                var grid        = ddSrc.view.grid;
                var targetDiv   = evtObj.getTarget();
                var targetIndex = grid.getView().findRowIndex(targetDiv);
                this.clearDDStyles(ddSrc);

                // is this a row?
                if (targetIndex !== false) {
                    var targetRow        = grid.getView().getRow(targetIndex);
                    var targetRowEl      = Ext.get(targetRow);
                    var targetRowHeight  = targetRowEl.getHeight();
                    var targetRowTop     = targetRowEl.getY();
                    var targetRowCtr     = targetRowTop + Math.floor(targetRowHeight / 2);
                    var mouseY           = evtObj.getXY()[1];

                    // below
                    if (mouseY >= targetRowCtr) {
                        this.point = 'below';
                        targetRowEl.addClass('gridRowInsertBottomLine');
                        targetRowEl.removeClass('gridRowInsertTopLine');
                    }
                    // above
                    else if (mouseY < targetRowCtr) {
                        this.point = 'above';
                        targetRowEl.addClass('gridRowInsertTopLine');
                        targetRowEl.removeClass('gridRowInsertBottomLine')
                    }
                    this.overRow = targetRowEl;
    //                this.targetIndex = targetIndex;
                }
                else if (targetIndex === false) {
                    targetIndex =  grid.store.getCount();
                }
                this.targetIndex = targetIndex;

                grid.body.addClass('gridBodyNotifyOver');

                return 'x-dd-drop-ok';
            },
            notifyOut : function(ddSrc) {
                var grid        = ddSrc.view.grid;
                grid.body.removeClass('gridBodyNotifyOver');
                this.clearDDStyles(ddSrc);
                delete this.point;
                delete this.targetIndex;
                return true;
            },
            clearDDStyles : function(ddSrc) {
                var grid        = ddSrc.view.grid;
                if (this.overRow) {
                    this.overRow.removeClass('gridRowInsertBottomLine');
                    this.overRow.removeClass('gridRowInsertTopLine');
                }
                grid.body.removeClass('gridBodyNotifyOver');
            },
            notifyDrop  : function(ddSrc, evtObj, ddData){
                var grid        = ddSrc.view.grid;
                var store       = grid.store;
                var records     = ddSrc.dragData.selections;
                var origIndex   = store.indexOf(records[0]);
                var targetIndex = this.targetIndex;

                if (typeof targetIndex === 'boolean' && targetIndex === false) {
                    targetIndex = store.getCount();
                }

                Ext.each(records, store.remove, store);

                if (origIndex < targetIndex && this.point == 'above') {
                    targetIndex--;
                }
                else if (origIndex > targetIndex && this.point == 'below') {
                    targetIndex++;
                }

                if (targetIndex > store.getCount()) {
                    targetIndex = store.getCount();
                }

                store.insert(targetIndex, records);

                this.clearDDStyles(ddSrc);


                return true;
            }
        };


        addonGrid.on('viewready',function(grid){

            var leftGridDropTarget   = new Ext.dd.DropZone(addonGrid.el, dropTargetCfg);
        });

// DON'T DELETE - USED FOR DEBUGGING
// NOTE: use below code to output all object events to
//            function captureEvents(observable) {
//                Ext.util.Observable.capture(
//                    observable,
//                    function(eventName) {
//                        if (!Ext.isIE) console.log(eventName);
//                    },
//                    this
//                );
//            }
//
//            //captureEvents(object);



            cboProductAddonStyle.on({
                render: {
                    scope: this,
                    fn: function(){

                         cboProductAddonStyle.setValue(productAddonStyle);
                    }

                }

            });



        };

        // form
        function createFormUI() {

            frmPackageTab = new Ext.TabPanel({

                plain:true,
                activeTab: 0,
                height: 250,
                anchor: "100% 100%",
                baseCls: 'x-plain',
                autoScroll: true,
                layoutOnTabChange: true,               
                defaults:   {bodyStyle:'padding:5px'},
                items:[
                        {
                            id: "tabPagePackageGeneral",
                            name: "tabPagePackageGeneral",
                            cls:'x-plain',
                            title:'Product General',
                            layout: "fit",
                            items: [tabPagePackageGeneral]
                        },
                        {
                            id: "tabPageAddons",
                            name: "tabPageAddons",
                            cls:'x-plain',
                            title:'Addons',
                            layout: "border",
                            style: "padding: 5px",
                            items:[
                                        {
                                            id: "productaddonsbordercenter",
                                            region: "center",
                                            collapsible: false,
                                            title: "Addons",
                                            height: 440,
                                            layout: "border",
                                            border: false,
                                            defaults: {border:false},
                                            items: [
                                                        {
                                                            region: "north",
                                                            height: 40,
                                                            items: [
                                                                       {
                                                                           layout: "column",
                                                                           border: false,
                                                                           defaults: {border:false},
                                                                           items: [  
                                                                                    {
                                                                                        columnWidth: .6,
                                                                                        border: false,
                                                                                        layout: "anchor",
                                                                                        border: false,
                                                                                        defaults: {border:false},
                                                                                        items : [{
                                                                                                    layout: "absolute",
                                                                                                    width: 360,
                                                                                                    height: 40,
                                                                                                    items: [{
                                                                                                                xtype: "label",
                                                                                                                text: "Add Addon",
                                                                                                                x: 5,
                                                                                                                y: 3
                                                                                                            },
                                                                                                            lovComboAddons,
                                                                                                            {
                                                                                                                                                                                                                            
                                                                                                                
                                                                                                                id: "addonAddButton",
                                                                                                                xtype: "button",
                                                                                                                text: "add",
                                                                                                                style: "float:left;padding-left:3px",
                                                                                                                x: 275,
                                                                                                                y: 0,
                                                                                                                listeners:{
                                                                                                                    click: function(){

                                                                                                                       moveAddonFromComboToGrid();
                                                                                                                        
                                                                                                                    }
                                                                                                                }
                                                                                                                
                                                                                                            }
                                                                                                            ]
                                                                                                 }
                                                                                                ]
                                                                                                 

                                                                                    },
                                                                                    {
                                                                                        columnWidth: .4,
                                                                                        border: false,
                                                                                        layout: "form",
                                                                                        items : [cboProductAddonStyle]

                                                                                    }
                                                                                   ]
                                                                       }
                                                                   ]
                                                        },
                                                        {
                                                            region: "center",
                                                            height: 400,
                                                            layout: "fit",
                                                            items: [addonGrid]
                                                        }

                                                    ]
                                        }
                                  ]

                        },{
                            id: "tabPageAdvanced",
                            name: "tabPageAdvanced",
                            title:'Advanced',
                            layout: "fit",
                            border: false,
                            items : [tabPageAdvanced]

                        }
                    ]
            });

            frmPackageTab.on("tabchange",function(theTabPanel,thePanel){


                if (win.isVisible() && thePanel.name=="tabPageAddons"){



                }else if (thePanel.name == "tabPageAdvanced"){

                    // if only one selected server then
                    // display the plugin fields for that server                   

                    if (hostManagerStore.data.length>0){

                        try {
                            cboSelectServerHostManager.setValue(hostManagerStore.data.items[0].data.serverid);
                            getHostManagerPluginFields();
                        }catch(e){}
                    }
                }               

            });

            frmPackage = new Ext.FormPanel({

                items: [frmPackageTab]
            });



        };

        // all ui
        function createUI(){

            productType="";
            serverIds="";
            pluginCollection = new Collection(); 
            createGeneralSettingsTabUI();
            createAddonUI();           
            createAdvanceTabUI();
            createFormUI();

        };

        /* Private Medthods End*/

        /* Public Methods and Properties*/
        return {


            init: function() {



                // create button used above the product list grid
                 var addProduct = new Ext.Button(
                    {

                        id:"addProduct",
                        renderTo:"addproduct",
                        text: lang('Add Product'),
                        iconAlign: 'left',
                        handler:function(){
                                closing = false;
                                update = false;
                                if (!myMask){
                                    myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
                                }
                                 myMask.show();
                                 productId = 0;

                                 packageWin =  new TableTypeWindow();
                                 packageWin.CreateWindow(false);
                                 myMask.hide();
                        }
                    }
                );

            },

            ShowEditProductWindow: function (prodId)
            {
                addonsRendered = false;
                closing=false;
                packageWin =  new TableTypeWindow();

                productId = prodId;
                update = true;

                if (!myMask){
                    myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
                }
                myMask.show();
                packageWin.CreateWindow(true,productId);

                packageWin.PopulateFields(productId);

               
            }

        };
         /* Public Methods and Properties End*/

}();


Ext.onReady(ClientExec.ProductSettings.init, ClientExec.ProductSettings, true);