viewingWhat = 'products';
manualProductGroup = '';
var selectedProductGroup = 0;
var initWindow;
var signupURL = '';
var addonStyle = 0;

Ext.onReady(function(){

    // Function to process the window request
    function productWindow(update){
        if(this instanceof productWindow){
            //this.update = update;
            this.CreateWindow = createWindow;
            this.LoadFields = loadFields;
            this.lazyLoadFile = lazyLoadFile;
            return true;
        }else{
            return new productWindow();
        }
    }
    productWin = new productWindow();

    // Set the window options & decide if we are adding or editing
    function createWindow(updating, id) {
        update = updating;
        if (updating) {
            buttonText = lang('Update');
            titleText = '&nbsp;&nbsp;'+lang('Edit Product');
        } else {
            buttonText = lang('Save');
            titleText = '&nbsp;&nbsp;'+lang('Add Product');
        }

        // Create the tabs
        tabs = new Ext.TabPanel({
            id:'tabpanel',
            layoutOnTabChange: true,
            xtype:'tabpanel',
            activeItem:0,
            border:false,
            anchor:'100% 100%',
            deferredRender:false,
            plain:true,
            defaults:{
                layout:'form',
                defaultType:'textfield'
            }
        });

        if(productType == 1) {
            var winHeight = 435;
        } else {
            var winHeight = 400;
        }

        // Create the form layout
        productWinForm = new Ext.FormPanel({
            id: 'productWinForm',
            labelAlign: 'top',
            frame:true,
            hideBorders:true,
            shadow:false,
            floating:false,
            height:winHeight,
            width: 650,
            items:[tabs]
        });

        // Create the window
        win = new Ext.Window({
            layout:'fit',
            title:titleText,
            width: 650,
            shadow:false,
            forceLayout:true,
            autoHeight:true,
            modal:true,
            closeAction:'hide',
            plain: true,
            items: [productWinForm],
            fbar: [
                    {
                        id: 'btnEditProductCancel',
                        disabled: true,
                        text: lang('Cancel'),
                        handler: function(){
                            win.hide();
                        }
                    },
                   {
                        id: 'btnEditProductSave',
                        disabled: true,
                        text: buttonText,
                        handler: function(){
                            processUpdateClick();
                        }
                    }
            ],
            listeners: {
                hide: function() {productWinForm.destroy();}
            }
        });

        win.show(this);
        
        productWinForm.el.mask('Preparing Window', 'x-mask-loading');
        LazyLoad.js('../templates/admin/views/admin/editProduct-GeneralTab.js', function () {
            tabs.add({
                id: 'generalTab',
                title:'General',
                items:[generalTabPanel]
            });
            productWinForm.el.unmask();
            tabs.setActiveTab('generalTab');
            productWin.lazyLoadFile(productType, id);
        });
        

    } // End CreateWindow function

    /**
     * Save/Update handler
     */
    function processUpdateClick() {
        var domainArrayData = {};
        var selectedServers = '';
        var pluginFieldData = null;

        // Check if we are a domain product and process the pricing accordingly
        if(productType == 3) {

            // Save the current grid incase we have any changes
            saveGridPricing(previousSelection);

            for(x=0;x<tld_store.getCount();x++){
                var workingArray = {};

                // Get the record and start saving the data
                var rec = tld_store.getAt(x);

                // DOn't bother adding the placeholder
                if(rec.get('tld') != '-- Select a TLD --') {

                    workingArray['tld'] = rec.get('tld');
                    workingArray['registrar'] = rec.get('registrar');
                    workingArray['isDefault'] = rec.get('isDefault');

                    // Process the pricing
                    var pricingArray = rec.get('pricing');
                    var finalPricingArray = {};
                    for (i=0;i<pricingArray.length;i++) {

                        var workingPricingArray = {};

                        // Actual Pricing Data
                        workingPricingArray['period'] = pricingArray[i].period;
                        workingPricingArray['period_id'] = pricingArray[i].period;
                        workingPricingArray['price'] = pricingArray[i].price;
                        workingPricingArray['transfer'] = pricingArray[i].transfer;
                        workingPricingArray['renew'] = pricingArray[i].renew;

                        finalPricingArray[i] = workingPricingArray;
                    }
                    workingArray['pricing'] = finalPricingArray;

                    domainArrayData[x] = workingArray;
                }
            }
        } else if(productType == 1) {

            // Specific workings for hosting products

            // Get the selected servers
            selectedServers = lovComboProductServers.getCheckedValue();

            // Process the currently selected plugin
            processContainerFields(selectedPlugin);
            // Save the fields
            pluginFieldData = Ext.encode(pluginFieldsFinal);

        }

        productWinForm.getForm().submit({
            clientValidation: true,
            url: 'index.php?fuse=admin&action=saveProduct&packageId='+productId+'&productType='+productType,
            params: {
                productGroup:selectedProductGroup,
                addons:getAddonPostParms(),
                domainPricing: Ext.util.JSON.encode(domainArrayData),
                selectedServers: selectedServers,
                pluginFieldData: pluginFieldData
            },
            success: function(form, action) {
               win.hide();
               gridstore.load();
            },
            failure: function(form, action) {
                switch (action.failureType) {
                    case Ext.form.Action.CLIENT_INVALID:
                        Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                        break;
                    case Ext.form.Action.CONNECT_FAILURE:
                        Ext.Msg.alert('Failure', 'Ajax communication failed');
                        break;
                    case Ext.form.Action.SERVER_INVALID:
                        Ext.Msg.alert('Failure', action.result.message);
               }
            }
        });
    }


    // Start loading the fields for the window only general tab
    function loadFields(id){
        
        if (id == -1 ) {
            Ext.getCmp('packageGroupName').setValue(manualProductGroup);
            Ext.getCmp('btnEditProductCancel').setDisabled(false);
            Ext.getCmp('btnEditProductSave').setDisabled(false);
            // Load Bundles
            bundleComboStore.load({params:{id:id}});
            return;
        }
        
        productWinForm.getForm().load({
            url: 'index.php?fuse=admin&action=Admin_GetProduct&packageid=' + productId,
            waitMsg:lang('Loading'),
            success: function(form, action) {
                // special loading rules
                var response = Ext.util.JSON.decode(action.response.responseText);

		selectedProductGroup = response.data.packageGroupId;
                signupURL = response.data.signupURL;

                if(response.data.addonStyle != null){
                    addonStyle = response.data.addonStyle;
                }else{
                    addonStyle = 0;
                }
                if(cboProductAddonStyle != undefined){
                    cboProductAddonStyle.setValue(addonStyle);
                }

                // Set the page title
                var title =  titleText + ' - ' +  response.data.packageName;
                win.setTitle(title);

                // Set the dropdown
                welcomeEmailDropdown.setValue(response.data.emailTemplateId);
                //tldpricing_store.loadData(response.data);
                
                // Load Bundles
                bundleComboStore.load({params:{id:id}});
                
                Ext.getCmp('btnEditProductCancel').setDisabled(false);
                Ext.getCmp('btnEditProductSave').setDisabled(false);

            },
            failure: function(form, action) {
                // Parse the errors for a failure
                var response = Ext.util.JSON.decode(action.response.responseText);
                if(response.error == true) {
                    Ext.MessageBox.alert(lang("Errors"), response.message);
                    win.hide();
                    gridstore.load();
                }
            }
        });
    }

    /*
     * Series of functions related to starting a new ExtJS window
     */

    // Function to lazy load the required JS files
    function lazyLoadFile(type, id) {
        // Choose what kind of tabs to load
        if(type == '0') {
            //General
            LazyLoad.js(['../templates/admin/views/admin/editProduct-AddonTab.js', '../templates/admin/views/admin/editProduct-General.js'], function () {
                prepareGeneralView(); // Generic function that can load ExtJS elements
                productWin.LoadFields(id);
            });
        } else if(type == '1') {
            // Hosting
            LazyLoad.js(['../templates/admin/views/admin/editProduct-AddonTab.js', '../templates/admin/views/admin/editProduct-Hosting.js'], function () {
                prepareHostingView(); // Generic function that can load ExtJS elements
                productWin.LoadFields(id);
            });
        } else if(type == '2') {
            // SSL
            LazyLoad.js(['../templates/admin/views/admin/editProduct-AddonTab.js',  '../templates/admin/views/admin/editProduct-SSL.js'], function () {
                prepareSSLView(); // Generic function that can load ExtJS elements
                productWin.LoadFields(id);
            });
        } else if(type == '3') {
            // Domains
            LazyLoad.js(['../templates/admin/views/admin/editProduct-AddonTab.js',  '../templates/admin/views/admin/editProduct-Domains.js'], function () {
                prepareDomainsView(); // Generic function that can load ExtJS elements
                productWin.LoadFields(id);
            });
        }
    }
    
    // Function to start the window
    initWindow = function(id){
        // Are we adding or editing
        if(id == -1) {
            productWin.CreateWindow(false, '-1');
        } else {
            productWin.CreateWindow(true, id);
        }
    }
});

/*
 * Functions to be called outside of the ExtJS OnReady. Mainly to add or edit the window
 */

// Function to load the Edit Product
function editProduct(id, type)
{
    // Lazy load the relevant product type and start the window
    //productWin.lazyLoadFile(type, id);
    productId = id;
    productType = type;
    initWindow(id);
}

// Function to load the Add Product window
function addProduct(type, groupName)
{
    // Lazy load the revelant product type and start the window
    //productWin.lazyLoadFile(type, -1);
    productType = type;
    productId = -1;
    initWindow(-1)
    manualProductGroup = groupName;
}