/*
 * Ext JS Library 3.0 RC1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */

var productWaitingMask;
var showProductWaitingMask;
var hideProductWaitingMask;

var today = new Date();
var dateToday = today.dateFormat(gDateFormat);
var hourToday = (today.dateFormat('H')).toString();
var minuteToday = (today.dateFormat('i')).toString();
var secondToday = (today.dateFormat('s')).toString();

var getCurrentProduct;
var AskAboutResettingRecurring;
var domainId = 0;
var editserver = true;
var packageStatus = null;
var domainData;
var altPrice = '0.00';
var resetgenerateinvoice = 0;
var fieldsContainer = {};
var addonsContainer = {};
var countriesValues;

var productWin;

var productFieldProductGroup;
var productFieldProduct;

var productFieldFieldsContainer;

var productFieldAddonsContainer;

var productFieldServer;
var productFieldPlugin;
var productFieldIpAddress;
var productFieldSharedIp;
var productFieldAvailableIps;
var productFieldDomainName;
var productFieldUserName;
var productFieldPassword;
var productFieldPasswordContainer;
var productFieldPasswordWarning;
var productFieldOverrideServerOptions;

var productFieldDateCreated;
var productFieldHourCreated;
var productFieldMinuteCreated;
var productFieldSecondCreated;
var productFieldDateCreatedContainer;
var productFieldRecurring;
var productFieldBillingCycle;
var productFieldNextDueDate;
var productFieldRecurringContainer;
var productFieldPriceOverride;
var productFieldPriceOverrideValidate;
var productFieldPriceOverrideCheckbox;

var productFieldTriggerServerPluginCheckbox;

Ext.onReady(function(){
    if(document.getElementById('addproductbutton') != null){
        new Ext.Button({
            id:"addproduct",
            renderTo:"addproductbutton",
            text: lang('Add Item'),
            menu:       new Ext.menu.Menu({
                            enableScrolling:  false,
                            shadow:false,
                            items:            [
                                {
                                    id:       'btnTopAddProduct',
                                    text:     lang("Product"),
                                    iconAlign: 'left',
                                    handler:  function(){
                                       addProduct();
                                    }
                                },
                                {
                                    id:       'btnTopAddDomain',
                                    text:     lang("Domain"),
                                    iconAlign: 'left',
                                    onClick:  function(){
                                        addDomain();
                                    }
                                }
                            ]
                        })

        });
    }
    
    createProductWin()
});

function createProductWin(){
    var defaultWidth  = 180;
    var defaultWidth2 = 300;
    var defaultWidth3 = 150;
    
// Product Group
    var productGroupStore = new Ext.data.JsonStore({
        root:           'productGroups',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
            groupsonly:         1,
            groupsWithPackages: 1
        },
        fields:         [
            'id',
            'name'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=admin&action=Admin_GetProductGroups'
        })
    });
    
    productGroupStore.setDefaultSort('id', 'asc');
    
    /*
    productGroupStore.on('load', function(data){
        productGroupStore_OnLoad();
    });
    */
    
    function productGroupStore_OnLoad()
    {
        var prodGrpId = '';
        
        if(domainData != undefined
          && validDomainData(domainData.promotionid)){
            prodGrpId = domainData.promotionid;
        }else if(productGroupStore.data.length > 0){
            prodGrpId = productGroupStore.data.items[0].data.id;
        }
        
        productFieldProductGroup.setValue(prodGrpId);
        productFieldProductGroupActions(prodGrpId);
    }
    
    productGroupStore.load();
    
    productFieldProductGroup = new Ext.form.ComboBox({
        id:               'productFieldProductGroup',
        name:             'productFieldProductGroup',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Product Group"),
        store:            productGroupStore,
        valueField:       'id',
        displayField:     'name',
        hiddenId:         'productGroupId',
        hiddenName:       'productGroupName',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false,
        listeners:        {
            select: productFieldProductGroup_OnSelect
        }
    });
    
    function productFieldProductGroup_OnSelect(combo, record, index)
    {
        var row = record.data;
        productFieldProductGroupActions(row.id);
    }
    
    function productFieldProductGroupActions(productgroup_id)
    {
        getGroupProducts(productgroup_id);
        getProductFields(productgroup_id);
    }
    
// Product
    var productStore = new Ext.data.JsonStore({
        root:           'products',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
            productgroup_id:  0
        },
        fields:         [
            'id',
            'name'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=admin&action=getGroupProducts'
        })
    });
    
    productStore.setDefaultSort('id', 'asc');
    
    productStore.on('load', function(data){
        var prodId = '';
        var domId = '';
        
        if(domainData != undefined
          && validDomainData(domainData.promotionid)
          && domainData.promotionid == productFieldProductGroup.getValue()
          && validDomainData(domainData.productid)){
            prodId = domainData.productid;
            domId = domainData.domainid;
        }else if(productStore.data.length > 0){
            prodId = productStore.data.items[0].data.id;
            domId = 0;
        }
        
        productFieldProduct.setValue(prodId);
        productFieldProduct.enable();
        getProductAddons(prodId);
        getProductServers(prodId, domId);
    });
    
    function getGroupProducts(productgroup_id)
    {
        productStore.removeAll();
        productFieldProduct.clearValue();
        productFieldProduct.disable();
        productStore.load({
            params: {
                productgroup_id:  productgroup_id
            }
        });
    }
    
    productFieldProduct = new Ext.form.ComboBox({
        id:               'productFieldProduct',
        name:             'productFieldProduct',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Product"),
        store:            productStore,
        valueField:       'id',
        displayField:     'name',
        hiddenId:         'productId',
        hiddenName:       'productName',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false,
        listeners:        {
            select: productFieldProduct_OnSelect
        }
    });
    
    function productFieldProduct_OnSelect(combo,record,index)
    {
        var prodId = record.data.id;
        getProductAddons(prodId);
        
        var domId = '';
        
        if(domainData != undefined
          && validDomainData(domainData.promotionid)
          && domainData.promotionid == productFieldProductGroup.getValue()
          && validDomainData(domainData.domainid)){
            domId = domainData.domainid;
        }else{
            domId = 0;
        }
        
        getProductServers(prodId, domId);
    }
    
// FIELDS TAB
// Fields
    var productFieldsStore = new Ext.data.JsonStore({
        root:           'productFields',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
            productgroup_id:    0,
            domainId:           domainId,
            getCountriesValues: 1
        },
        fields:         [
            'name',
            'value',
            'id',
            'type',
            'isrequired',
            'dropdownoptions'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=clients&action=adminGetClientProductFields'
        })
    });
    
    productFieldsStore.setDefaultSort('id', 'asc');
    
    productFieldsStore.on('load', function(data){
        for(var iterator = 0; iterator < productFieldsStore.data.length; iterator++){
            var currentFieldData = productFieldsStore.getAt(iterator).data;
            var currentFieldValue = currentFieldData.value;
            
            if(currentFieldData.isrequired == 1){
                var allowBlankValue = false;
            }else{
                var allowBlankValue = true;
            }
            
            switch(currentFieldData.type){
                case '0':   // typeTEXTFIELD
                    fieldsContainer[currentFieldData.name] = new Ext.form.TextField({
                        id:               'CT_' + currentFieldData.id,
                        name:             'CT_' + currentFieldData.id,
                        dataType:         currentFieldData.type,
                        fieldLabel:       currentFieldData.name,
                        //validationEvent:  false,
                        width:            defaultWidth2,
                        border:           false,
                        value:            currentFieldValue,
                        allowBlank:       allowBlankValue,
                        blankText:        lang("This field is required")
                    });
                    
                    productFieldFieldsContainer.add(fieldsContainer[currentFieldData.name]);
                    break;
                case '1':   // typeYESNO
                case '6':   // typeCOUNTRY
                case '9':   // typeDROPDOWN
                    var storeObject = {};
                    
                    switch(currentFieldData.type){
                        case '1':   // typeYESNO
                            storeObject = [
                                [
                                    0,
                                    lang('No')
                                ],
                                [
                                    1,
                                    lang('Yes')
                                ]
                            ];
                            break;
                        case '6':   // typeCOUNTRY
                            if(countriesValues == undefined){
                                countriesValues = currentFieldData.dropdownoptions;
                            }
                            
                            storeObject = countriesValues;
                            break;
                        case '9':   // typeDROPDOWN
                            storeObject = currentFieldData.dropdownoptions;
                            break;
                    }
                    
                    fieldsContainer[currentFieldData.name] = new Ext.form.ComboBox({
                        id:               'CT_' + currentFieldData.id,
                        name:             'CT_' + currentFieldData.id,
                        dataType:         currentFieldData.type,
                        typeAhead:        true,
                        triggerAction:    'all',
                        lazyRender:       true,
                        mode:             'local',
                        //validationEvent:  false,
                        width:            defaultWidth2,
                        fieldLabel:       currentFieldData.name,
                        store:            storeObject,
                        allowBlank:       allowBlankValue,
                        blankText:        lang("This field is required"),
                        forceSelection:   true,
                        editable:         false,
                        selectOnFocus:    true,
                        value:            currentFieldValue
                    });
                    
                    productFieldFieldsContainer.add(fieldsContainer[currentFieldData.name]);
                    break;
                case '10':  // typeTEXTAREA
                    fieldsContainer[currentFieldData.name] = new Ext.form.TextArea({
                        id:               'CT_' + currentFieldData.id,
                        name:             'CT_' + currentFieldData.id,
                        dataType:         currentFieldData.type,
                        fieldLabel:       currentFieldData.name,
                        border:           false,
                        //validationEvent:  false,
                        allowBlank:       allowBlankValue,
                        blankText:        lang("This field is required"),
                        width:            defaultWidth2,
                        height:           100,
                        value:            currentFieldValue
                    });
                    
                    productFieldFieldsContainer.add(fieldsContainer[currentFieldData.name]);
                    break;
                case '15':  //  typeDATE
                    if(currentFieldValue != '' && currentFieldValue != '00/00/0000'){
                        //currentFieldValue = (new Date(Date.parse(currentFieldValue))).dateFormat(gDateFormat);
                        currentFieldValue = currentFieldValue;
                    }else{
                        currentFieldValue = '';
                    }
                    
                    fieldsContainer[currentFieldData.name] = new Ext.form.DateField({
                        id:               'CT_' + currentFieldData.id,
                        name:             'CT_' + currentFieldData.id,
                        dataType:         currentFieldData.type,
                        fieldLabel:       currentFieldData.name,
                        //validationEvent:  false,
                        height:           "5px",
                        selectOnFocus:    true,
                        format:           gDateFormat,
                        value:            currentFieldValue,
                        allowBlank:       allowBlankValue,
                        blankText:        lang("This field is required")
                    });
                    
                    productFieldFieldsContainer.add(fieldsContainer[currentFieldData.name]);
                    break;
            }
        }
        
        if(productFieldFieldsContainer.items.length == 0){
            disableTab('tabPanelFields');
        }else{
            Ext.getCmp('productTabPanels').unhideTabStripItem('tabPanelFields');
            Ext.getCmp('productTabPanels').findById('tabPanelFields').enable();
            
            if(Ext.getCmp('productTabPanels').getActiveTab().id == 'tabPanelFields'){
                productFieldFieldsContainer.doLayout();
            }
        }
    });
    
    function getProductFields(productgroup_id)
    {
        productFieldsStore.removeAll();
        
        productFieldFieldsContainer.removeAll(true);
        productFieldFieldsContainer.doLayout();
        fieldsContainer = {};
        
        var getCountriesValues = 1;
        
        if(countriesValues != undefined){
            getCountriesValues = 0;
        }
        
        productFieldsStore.load({
            params: {
                productgroup_id:    productgroup_id,
                domainId:           domainId,
                getCountriesValues: getCountriesValues
            }
        });
    }
    
    productFieldFieldsContainer = new Ext.Container({
        id:         'productFieldFieldsContainer',
        autoScroll: true,
        layout:     'form',
        items : [
        ]
    });
    
// ADDONS TAB
// Addons
    var productAddonsStore = new Ext.data.JsonStore({
        root:           'productAddons',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
            domainId:       domainId,
            packageId:      0,
            packageTypeId:  0,
            billingCycle:   0
        },
        fields:         [
            'name',
            'description',
            'id',
            'dropdownoptions',
            'value'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=clients&action=Admin_GetClientProductAddons'
        })
    });
    
    productAddonsStore.setDefaultSort('id', 'asc');
    
    productAddonsStore.on('load', function(data){
        for(var iterator = 0; iterator < productAddonsStore.data.length; iterator++){
            var currentAddonData = productAddonsStore.getAt(iterator).data;
            
            var currentFieldLabel = currentAddonData.name;
            
            var helpAddon = currentAddonData.description;
            
            if(helpAddon != ''){
                currentFieldLabel = "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpAddon.replace(/'/g, "&#39;") + "'>" + currentAddonData.name + "</span>";
            }
            
            addonsContainer[currentAddonData.name] = new Ext.form.ComboBox({
                id:               'ADDON_' + currentAddonData.id,
                name:             'ADDON_' + currentAddonData.id,
                typeAhead:        true,
                triggerAction:    'all',
                lazyRender:       true,
                mode:             'local',
                //validationEvent:  false,
                width:            defaultWidth2,
                fieldLabel:       currentFieldLabel,
                store:            currentAddonData.dropdownoptions,
                allowBlank:       false,
                blankText:        lang("This field is required"),
                forceSelection:   true,
                editable:         false,
                selectOnFocus:    true,
                value:            currentAddonData.value
            });
            
            productFieldAddonsContainer.add(addonsContainer[currentAddonData.name]);
        }
        
        if(productFieldAddonsContainer.items.length == 0){
            disableTab('tabPanelAddons');
        }else{
            Ext.getCmp('productTabPanels').unhideTabStripItem('tabPanelAddons');
            Ext.getCmp('productTabPanels').findById('tabPanelAddons').enable();
            
            if(Ext.getCmp('productTabPanels').getActiveTab().id == 'tabPanelAddons'){
                productFieldAddonsContainer.doLayout();
            }
        }
    });
    
    function getProductAddons(product_id)
    {
        productAddonsStore.removeAll();
        
        productFieldAddonsContainer.removeAll(true);
        productFieldAddonsContainer.doLayout();
        addonsContainer = {};
        
        var paymentTerm = 0;
        
        if(productFieldRecurring.getValue() == 1){
            paymentTerm = productFieldBillingCycle.getValue();
        }
        
        productAddonsStore.load({
            params: {
                domainId:       domainId,
                packageId:      product_id,
                packageTypeId:  productFieldProductGroup.getValue(),
                billingCycle:   paymentTerm
            }
        });
    }
    
    productFieldAddonsContainer = new Ext.Container({
        id:         'productFieldAddonsContainer',
        autoScroll: true,
        layout:     'form',
        items : [
        ]
    });
    
// SERVER TAB
// Server
    var productServerStore = new Ext.data.JsonStore({
        root:           'servers',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
            product_id: 0,
            domain_id:  0
        },
        fields:         [
            'id',
            'name',
            'plugin',
            'sharedip'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=clients&action=Admin_GetClientProductServers'
        })
    });
    
    productServerStore.setDefaultSort('id', 'asc');
    
    productServerStore.on('load', function(data){
        var serverId = '';
        var serverPlugin = '';
        
        if(domainData != undefined
          && validDomainData(domainData.productid)
          && validDomainData(domainData.serverid)
          && (domainData.productid == productFieldProduct.getValue()
          || serverInStore(productServerStore, domainData.serverid))){
            serverId = domainData.serverid;
          
            if(validDomainData(domainData.serverplugin)){
                serverPlugin = domainData.serverplugin;
            }
        }else if(productServerStore.data.length > 0){
            serverId = productServerStore.data.items[0].data.id;
            serverPlugin = productServerStore.data.items[0].data.plugin;
        }
        
        if(serverId == ''
          || serverId == '0'){
            serverId = 0;
        }
        
        if(serverId == 0
          && (productServerStore.data.length == 0
          || (productServerStore.data.length == 1
          && productServerStore.data.items[0].data.id == 0))){
            productFieldServer.setValue(0);
            
            if(editserver){
                productFieldServer.enable();
            }
            
            disableTab('tabPanelServer');
        }else{
            Ext.getCmp('productTabPanels').unhideTabStripItem('tabPanelServer');
            Ext.getCmp('productTabPanels').findById('tabPanelServer').enable();
            
            productFieldServer.setValue(serverId);
            
            if(editserver){
                productFieldServer.enable();
            }
            
            if(serverId != 0){
                getPlugin(serverPlugin);
                getServerIPs(serverId);
            }
        }
    });
    
    function serverInStore(serverStore, serverId){
        for(var iterator = 0; iterator < serverStore.data.items.length; iterator++){
            if(serverStore.data.items[iterator].data.id == serverId){
                return true;
            }
        }
        
        return false;
    }
    
    function getProductServers(product_id, domain_id)
    {
        productServerStore.removeAll();
        productFieldPlugin.setText("Plugin: " + lang("None"));
        productFieldServer.clearValue();
        productFieldServer.disable();
        productServerStore.load({
            params: {
                product_id: product_id,
                domain_id:   domain_id
            }
        });
    }
    
    productFieldServer = new Ext.form.ComboBox({
        id:               'productFieldServer',
        name:             'productFieldServer',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Server"),
        store:            productServerStore,
        valueField:       'id',
        displayField:     'name',
        hiddenId:         'serverId',
        hiddenName:       'serverName',
        forceSelection:   true,
        editable:         false,
        listeners:        {
            select: productFieldServer_OnSelect
        }
    });
    
    function productFieldServer_OnSelect(combo,record,index)
    {
        getPlugin(record.data.plugin);
        getServerIPs(record.data.id);
    }
    
// Server Plugin
    productFieldPlugin = new Ext.form.Label({
        id:         'productFieldPlugin',
        name:       'productFieldPlugin',
        hideLabel:  true,
        text:       "Plugin: " + lang('None')
    });
    
    function getPlugin(server_plugin)
    {
        if(server_plugin == ""){
            server_plugin = lang("None");
        }
        
        productFieldPlugin.setText("Plugin: " + server_plugin);
    }
    
// Ip Address
    var helpIpAddress = lang('You can only use the server shared IP, or one of the available IPs listed below. If you need to add a new IP to the list, please visit the Servers page.');
    
    productFieldIpAddress = new Ext.form.TextField({
        id:               'productFieldIpAddress',
        name:             'productFieldIpAddress',
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpIpAddress.replace(/'/g, "&#39;") + "'>" + lang("Ip Address") + "</span>",
        validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        value:            '',
        disabled:         true
        //allowBlank:       false
    });
    
// Use Shared Ip
    productFieldSharedIp = new Ext.form.Checkbox({
        id:               'productFieldSharedIp',
        name:             'productFieldSharedIp',
        value:            true,
        validationEvent:  false,
        hideLabel:        true,
        boxLabel:         lang('Use Shared Ip'),
        listeners: {
            check:  productFieldSharedIp_OnCheck
        }
    });
    
    function productFieldSharedIp_OnCheck(ckBox,isChecked){
        getSharedIP();
    }
    
    function getSharedIP()
    {
        if(productFieldSharedIp.getValue() == true){
            var selectedServerId = productFieldServer.getValue();
            var sharedip = '';
            
            var record = productServerStore.getById(selectedServerId);
            
            if(record != undefined){
                sharedip = record.data.sharedip;
            }
            
            productFieldIpAddress.setValue(sharedip);
            productFieldAvailableIps.clearValue();
            productFieldAvailableIps.setDisabled(true);
        }else{
            productFieldIpAddress.setValue('');
            
            if(editserver){
                productFieldAvailableIps.setDisabled(false);
            }
            setServerIP();
        }
    }
    
// Available Ips
    var productServerIpStore = new Ext.data.JsonStore({
        root:           'serverips',
        totalProperty:  'totalcount',
        idProperty:     'serverid',
        remoteSort:     true,
        baseParams:     {
            domain_id:  domainId,
            server_id:  0
        },
        fields:         [
            'serverid',
            'ip'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=clients&action=Admin_GetClientProductServerIps'
        })
    });
    
    productServerIpStore.setDefaultSort('id', 'asc');
    
    productServerIpStore.on('load', function(data){
        getSharedIP();
    });
    
    function setServerIP(){
        var serverId = '';
        var serverIp = '';
        
        if(domainData != undefined
          && validDomainData(domainData.serverid)
          && domainData.serverid == productFieldServer.getValue()
          && validDomainData(domainData.ipaddress)){
            serverId = domainData.ipaddress;
            serverIp = domainData.ipaddress;
        }else if(productServerIpStore.data.length > 0){
            serverId = productServerIpStore.data.items[0].data.serverid;
            serverIp = productServerIpStore.data.items[0].data.ip;
        }
        
        productFieldAvailableIps.setValue(serverId);
        productFieldIpAddress.setValue(serverIp);
    }
    
    function getServerIPs(server_id){
        productServerIpStore.load({
            params: {
                server_id:  server_id,
                domain_id:  domainId
            }
        });
    }
    
    productFieldAvailableIps = new Ext.form.ComboBox({
        id:               'productFieldAvailableIps',
        name:             'productFieldAvailableIps',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Available Ips"),
        store:            productServerIpStore,
        valueField:       'serverid',
        displayField:     'ip',
        hiddenId:         'productserverip',
        hiddenName:       'productip',
        //allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false,
        listeners:        {
            select: productFieldAvailableIps_OnSelect
        }
    });
    
    function productFieldAvailableIps_OnSelect(combo,record,index){
        productFieldIpAddress.setValue(record.data.ip);
    }
    
// Domain Name
    var helpDomainName = lang('It is not possible to edit the domain associated with this package once it has been activated and the domain in question has been registered');
    
    productFieldDomainName = new Ext.form.TextField({
        id:               'productFieldDomainName',
        name:             'productFieldDomainName',
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpDomainName.replace(/'/g, "&#39;") + "'>" + lang("Domain Name") + "</span>",
        //validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        value:            ''
        //allowBlank:       false
    });
    
// User Name
    productFieldUserName = new Ext.form.TextField({
        id:               'productFieldUserName',
        name:             'productFieldUserName',
        fieldLabel:       lang("User Name"),
        //validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        //allowBlank:       false,
        value:            ''
    });
    
// Password
    productFieldPassword = new Ext.form.TextField({
        id:               'productFieldPassword',
        name:             'productFieldPassword',
        fieldLabel:       lang("Password"),
        //validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        //allowBlank:       false,
        value:            ''
    });
    
    productFieldPasswordContainer = new Ext.Container({
        id:     'productFieldPasswordContainer',
        layout: 'form',
        items : [
            productFieldPassword
        ]
    });
    
    productFieldPasswordWarning = new Ext.form.FieldSet({
        id:           'productFieldPasswordWarning',
        name:         'productFieldPasswordWarning',
        title:        lang('Warning'),
        autoHeight:   true,
        labelAlign:   'top',
        items :       [
            {
                xtype:          "label",
                id:             'PasswordWarning',
                name:           'PasswordWarning',
                fieldLabel:     lang('Domain passwords are encrypted, but the mcrypt extension is not enabled.'),
                labelStyle:     "font-weight: bold;",
                labelSeparator: ''
                //text:           '',
                //style:          "font-weight: bold;"
            }
        ],
        hideMode:     'offsets',
        hidden:       true
    });
    
// Override Server Options
    productFieldOverrideServerOptions = new Ext.form.Checkbox({
        id:               'productFieldOverrideServerOptions',
        name:             'productFieldOverrideServerOptions',
        value:            false,
        validationEvent:  false,
        hideLabel:        true,
        boxLabel:         "<b>" + lang('Override Server Options') + "</b>",
        hidden:           true,
        listeners: {
            check:  productFieldOverrideServerOptions_OnCheck
        }
    });
    
    function productFieldOverrideServerOptions_OnCheck(ckBox,isChecked){
        if(productFieldOverrideServerOptions.getValue() == true){
            Ext.Msg.show({
                title:    "Override Server Options?",
                msg:      lang("WARNING: plugins might get out of sync.<br>Are you sure you want to override the server information?"),
                buttons:  Ext.Msg.YESNO,
                fn:       function(btn, text){
                    if(btn == 'yes'){
                        productFieldOverrideServerOptions.hide();
                        editserver = true;
                        
                        productFieldServer.enable();
                        
                        if(productFieldDomainName.editdomain){
                            productFieldDomainName.enable();
                        }
                        
                        productFieldSharedIp.enable();
                        
                        if(productFieldSharedIp.getValue() != true){
                            productFieldAvailableIps.enable();
                        }
                        
                        productFieldUserName.enable();
                        productFieldPassword.enable();
                    }else{
                        productFieldOverrideServerOptions.setValue(false);
                    }
                },
                icon:     Ext.MessageBox.WARNING
            });
        }
    }
    
// BILLING TAB
// Date Created
    productFieldDateCreated = new Ext.form.DateField({
        id:               'productFieldDateCreated',
        name:             'productFieldDateCreated',
        fieldLabel:       lang("Date Created"),
        validationEvent:  false,
        height:           "5px",
        selectOnFocus:    true,
        format:           gDateFormat,
        value:            dateToday,
        allowBlank:       false,
        anchor:           '98%'
    });
    
    productFieldHourCreated = new Ext.form.ComboBox({
        id:               'productFieldHourCreated',
        name:             'productFieldHourCreated',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        hideLabel:        true,
        validationEvent:  false,
        width:            50,
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'name'
            ],
            data:     [
                ['00', '00'],
                ['01', '01'],
                ['02', '02'],
                ['03', '03'],
                ['04', '04'],
                ['05', '05'],
                ['06', '06'],
                ['07', '07'],
                ['08', '08'],
                ['09', '09'],
                ['10', '10'],
                ['11', '11'],
                ['12', '12'],
                ['13', '13'],
                ['14', '14'],
                ['15', '15'],
                ['16', '16'],
                ['17', '17'],
                ['18', '18'],
                ['19', '19'],
                ['20', '20'],
                ['21', '21'],
                ['22', '22'],
                ['23', '23']
            ]
        }),
        valueField:       'id',
        displayField:     'name',
        value:            hourToday,
        hiddenId:         'productFieldHourCreatedId',
        hiddenName:       'productFieldHourCreatedName',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
    productFieldMinuteCreated = new Ext.form.ComboBox({
        id:               'productFieldMinuteCreated',
        name:             'productFieldMinuteCreated',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        hideLabel:        true,
        validationEvent:  false,
        width:            50,
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'name'
            ],
            data:     [
                ['00', '00'],
                ['01', '01'],
                ['02', '02'],
                ['03', '03'],
                ['04', '04'],
                ['05', '05'],
                ['06', '06'],
                ['07', '07'],
                ['08', '08'],
                ['09', '09'],
                ['10', '10'],
                ['11', '11'],
                ['12', '12'],
                ['13', '13'],
                ['14', '14'],
                ['15', '15'],
                ['16', '16'],
                ['17', '17'],
                ['18', '18'],
                ['19', '19'],
                ['20', '20'],
                ['21', '21'],
                ['22', '22'],
                ['23', '23'],
                ['24', '24'],
                ['25', '25'],
                ['26', '26'],
                ['27', '27'],
                ['28', '28'],
                ['29', '29'],
                ['30', '30'],
                ['31', '31'],
                ['32', '32'],
                ['33', '33'],
                ['34', '34'],
                ['35', '35'],
                ['36', '36'],
                ['37', '37'],
                ['38', '38'],
                ['39', '39'],
                ['40', '40'],
                ['41', '41'],
                ['42', '42'],
                ['43', '43'],
                ['44', '44'],
                ['45', '45'],
                ['46', '46'],
                ['47', '47'],
                ['48', '48'],
                ['49', '49'],
                ['50', '50'],
                ['51', '51'],
                ['52', '52'],
                ['53', '53'],
                ['54', '54'],
                ['55', '55'],
                ['56', '56'],
                ['57', '57'],
                ['58', '58'],
                ['59', '59']
            ]
        }),
        valueField:       'id',
        displayField:     'name',
        value:            minuteToday,
        hiddenId:         'productFieldMinuteCreatedId',
        hiddenName:       'productFieldMinuteCreatedName',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
    productFieldSecondCreated = new Ext.form.ComboBox({
        id:               'productFieldSecondCreated',
        name:             'productFieldSecondCreated',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        hideLabel:        true,
        validationEvent:  false,
        width:            50,
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'name'
            ],
            data:     [
                ['00', '00'],
                ['01', '01'],
                ['02', '02'],
                ['03', '03'],
                ['04', '04'],
                ['05', '05'],
                ['06', '06'],
                ['07', '07'],
                ['08', '08'],
                ['09', '09'],
                ['10', '10'],
                ['11', '11'],
                ['12', '12'],
                ['13', '13'],
                ['14', '14'],
                ['15', '15'],
                ['16', '16'],
                ['17', '17'],
                ['18', '18'],
                ['19', '19'],
                ['20', '20'],
                ['21', '21'],
                ['22', '22'],
                ['23', '23'],
                ['24', '24'],
                ['25', '25'],
                ['26', '26'],
                ['27', '27'],
                ['28', '28'],
                ['29', '29'],
                ['30', '30'],
                ['31', '31'],
                ['32', '32'],
                ['33', '33'],
                ['34', '34'],
                ['35', '35'],
                ['36', '36'],
                ['37', '37'],
                ['38', '38'],
                ['39', '39'],
                ['40', '40'],
                ['41', '41'],
                ['42', '42'],
                ['43', '43'],
                ['44', '44'],
                ['45', '45'],
                ['46', '46'],
                ['47', '47'],
                ['48', '48'],
                ['49', '49'],
                ['50', '50'],
                ['51', '51'],
                ['52', '52'],
                ['53', '53'],
                ['54', '54'],
                ['55', '55'],
                ['56', '56'],
                ['57', '57'],
                ['58', '58'],
                ['59', '59']
            ]
        }),
        valueField:       'id',
        displayField:     'name',
        value:            secondToday,
        hiddenId:         'productFieldSecondCreatedId',
        hiddenName:       'productFieldSecondCreatedName',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
    productFieldDateCreatedContainer = new Ext.Container({
        id:     'productFieldDateCreatedContainer',
        layout: 'form',
        items : [
            {
                layout: 'column',
                border: false,
                items:  [
                    {
                        columnWidth:  .5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            productFieldDateCreated
                        ]
                    },
                    {
                        columnWidth:  .13,
                        layout:       'form',
                        border:       false,
                        items:        [
                            productFieldHourCreated
                        ]
                    },
                    {
                        columnWidth:  .02,
                        layout:       'form',
                        border:       false,
                        items:        [
                            {
                                xtype:      "label",
                                id:         'productFieldTimeSeparator1',
                                name:       'productFieldTimeSeparator1',
                                hideLabel:  true,
                                text:       ":  "
                            }
                        ]
                    },
                    {
                        columnWidth:  .13,
                        layout:       'form',
                        border:       false,
                        items:        [
                            productFieldMinuteCreated
                        ]
                    },
                    {
                        columnWidth:  .02,
                        layout:       'form',
                        border:       false,
                        items:        [
                            {
                                xtype:      "label",
                                id:         'productFieldTimeSeparator2',
                                name:       'productFieldTimeSeparator2',
                                hideLabel:  true,
                                text:       ":  "
                            }
                        ]
                    },
                    {
                        columnWidth:  .13,
                        layout:       'form',
                        border:       false,
                        items:        [
                            productFieldSecondCreated
                        ]
                    }
                ]
            }
        ]
    });
    
// Recurring
    var helpRecurring = lang('Setting this domain as recurring will allow you to set a billing cycle you want this domain to be billed with.') + '<br><br>' + lang('Note') + ': ' + lang('You need to generate invoices before recurring invoices get processed');
    
    productFieldRecurring = new Ext.form.ComboBox({
        id:               'productFieldRecurring',
        name:             'productFieldRecurring',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpRecurring.replace(/'/g, "&#39;") + "'>" + lang("Recurring") + "</span>",
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'name'
            ],
            data:     [
                [
                    0,
                    lang('No')
                ],
                [
                    1,
                    lang('Yes')
                ]
            ]
        }),
        valueField:       'id',
        displayField:     'name',
        value:            1,
        hiddenId:         'productFieldRecurringId',
        hiddenName:       'productFieldRecurringName',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false,
        listeners:        {
            select: productFieldRecurring_OnSelect
        }
    });
    
    function productFieldRecurring_OnSelect(combo, record, index)
    {
        var row = record.data;
        
        if(row.id == 1){
            showProductFieldRecurringContainer();
            productFieldRecurringContainer.doLayout();
        }else{
            hideProductFieldRecurringContainer();
        }
        
        getProductAddons(productFieldProduct.getValue());
    }
    
// Billing Cycle
    productFieldBillingCycle = new Ext.form.ComboBox({
        id:               'productFieldBillingCycle',
        name:             'productFieldBillingCycle',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Billing Cycle"),
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'cycle',
                'name'
            ],
            data:     [
                [
                    1,
                    lang('Monthly')
                ],
                [
                    3,
                    lang('Quarterly')
                ],
                [
                    6,
                    lang('Semiannually')
                ],
                [
                    12,
                    lang('Annually')
                ],
                [
                    24,
                    lang('Every 2 Years')
                ]
            ]
        }),
        valueField:       'cycle',
        displayField:     'name',
        value:            1,
        hiddenId:         'productFieldBillingCycleId',
        hiddenName:       'productFieldBillingCycleName',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false,
        listeners:        {
            select: productFieldBillingCycle_OnSelect
        }
    });
    
    function productFieldBillingCycle_OnSelect(combo, record, index)
    {
        getProductAddons(productFieldProduct.getValue());
    }
    
// Next Due Date
    productFieldNextDueDate = new Ext.form.DateField({
        id:               'productFieldNextDueDate',
        name:             'productFieldNextDueDate',
        fieldLabel:       lang("Next Due Date"),
        validationEvent:  false,
        height:           "5px",
        selectOnFocus:    true,
        format:           gDateFormat,
        value:            dateToday,
        allowBlank:       false
    });
    
// Recurring Container
    productFieldRecurringContainer = new Ext.Container({
        id:     'productFieldRecurringContainer',
        layout: 'form',
        items : [
        ]
    });
    
    function showProductFieldRecurringContainer()
    {
        if(productFieldRecurringContainer.items.length == 0){
            productFieldRecurringContainer.add(productFieldBillingCycle);
            productFieldRecurringContainer.add(productFieldNextDueDate);
            productFieldRecurringContainer.add(
                {
                    layout: 'column',
                    border: false,
                    items:  [
                        {
                            columnWidth:  .9,
                            layout:       'form',
                            border:       false,
                            items:        [
                                productFieldPriceOverride
                            ]
                        },
                        {
                            columnWidth:  .1,
                            layout:       'form',
                            border:       false,
                            items:        [
                                productFieldPriceOverrideCheckbox
                            ]
                        }
                    ]
                }
            );
        }else{
            productFieldRecurringContainer.show();
        }
    }
    
    function hideProductFieldRecurringContainer()
    {
        if(productFieldRecurringContainer.items.length > 0){
            productFieldRecurringContainer.hide();
        }
    }
    
// Price Override
    var helpPriceOverride = lang('Checking this box will allow you to override the default price for this package for this client only.');
    
    productFieldPriceOverride = new Ext.form.TextField({
        id:               'productFieldPriceOverride',
        name:             'productFieldPriceOverride',
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpPriceOverride.replace(/'/g, "&#39;") + "'>" + lang("Price Override") + "</span>",
        validationEvent:  false,
        width:            defaultWidth3,
        border:           false,
        value:            '',
        disabled:         true
        //allowBlank:       false
    });
    
    productFieldPriceOverrideValidate = function(){
        if(productFieldPriceOverride != undefined){
            if(productFieldPriceOverride.getValue() != ""){
                if(isNaN(productFieldPriceOverride.getValue()) || productFieldPriceOverride.getValue() < 0){
                    productFieldPriceOverride.markInvalid('This field has a wrong format or is not valid');
                    return false;
                }else{
                    productFieldPriceOverride.clearInvalid();
                    return true;
                }
            }else{
                productFieldPriceOverride.markInvalid('This field is required');
                return false;
            }
        }else{
            return false;
        }
    }
    
// Price Override Checkbox
    productFieldPriceOverrideCheckbox = new Ext.form.Checkbox({
        id:               'productFieldPriceOverrideCheckbox',
        name:             'productFieldPriceOverrideCheckbox',
        value:            false,
        validationEvent:  false,
        hideLabel:        true,
        listeners: {
            check:  productFieldPriceOverrideCheckbox_OnCheck
        }
    });
    
    function productFieldPriceOverrideCheckbox_OnCheck(ckBox,isChecked){
        if(productFieldPriceOverrideCheckbox.getValue() == true){
            productFieldPriceOverride.setValue(altPrice);
            productFieldPriceOverride.setDisabled(false);
        }else{
            altPrice = productFieldPriceOverride.getValue();
            
            if(altPrice == ''){
                altPrice = '0.00';
            }
            
            productFieldPriceOverride.setValue('');
            productFieldPriceOverride.setDisabled(true);
        }
    }

// tabed form
    var simpleForm = new Ext.FormPanel({
        frame:        true,
        hideBorders:  true,
        shadow:       false,
        floating:     false,
        autoHeight:   true,
        title:        '',
        bodyStyle:    'padding:5px 5px 0',
        width:        600,
        items:        [
            {
                layout:     'column',
                border:     false,
                labelAlign: 'top',
                items:  [
                    {
                        columnWidth:  .5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            productFieldProductGroup
                        ]
                    },
                    {
                        columnWidth:  .5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            productFieldProduct
                        ]
                    }
                ]
            },
            productFieldDateCreatedContainer,
            {
                id:             'productTabPanels',
                xtype:          'tabpanel',
                plain:          true,
                activeTab:      'tabPanelFields',
                //deferredRender: false,
                height:         280,
                defaults:       {bodyStyle:'padding:10px; background-color:WhiteSmoke'},
                items:          [
                    {
                        id:     'tabPanelBilling',
                        title:  lang("Billing"),
                        layout: 'form',
                        items:  [
                            {
                                layout: 'column',
                                border: false,
                                items:  [
                                    {
                                        columnWidth:  .7,
                                        layout:       'form',
                                        border:       false,
                                        items:        [
                                            productFieldRecurring,
                                            productFieldRecurringContainer
                                        ]
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        id:         'tabPanelFields',
                        title:      lang("Fields"),
                        layout:     'fit',
                        items:      [
                            productFieldFieldsContainer
                        ]
                    },
                    {
                        id:         'tabPanelAddons',
                        title:      lang("Addons"),
                        layout:     'fit',
                        items:      [
                            productFieldAddonsContainer
                        ]
                    },
                    {
                        id:     'tabPanelServer',
                        title:  lang("Server"),
                        layout: 'form',
                        items:  [
                            {
                                layout: 'column',
                                border: false,
                                items:  [
                                    {
                                        columnWidth:  .7,
                                        layout:       'form',
                                        border:       false,
                                        items:        [
                                            productFieldServer
                                        ]
                                    },
                                    {
                                        columnWidth:  .3,
                                        layout:       'form',
                                        border:       false,
                                        items:        [
                                            productFieldPlugin
                                        ]
                                    }
                                ]
                            },
                            {
                                layout: 'column',
                                border: false,
                                items:  [
                                    {
                                        columnWidth:  .7,
                                        layout:       'form',
                                        border:       false,
                                        items:        [
                                            productFieldIpAddress
                                        ]
                                    },
                                    {
                                        columnWidth:  .3,
                                        layout:       'form',
                                        border:       false,
                                        items:        [
                                            productFieldSharedIp
                                        ]
                                    }
                                ]
                            },
                            {
                                layout: 'column',
                                border: false,
                                items:  [
                                    {
                                        columnWidth:  .7,
                                        layout:       'form',
                                        border:       false,
                                        items:        [
                                            productFieldAvailableIps,
                                            productFieldDomainName,
                                            productFieldUserName,
                                            productFieldPasswordContainer
                                        ]
                                    }
                                ]
                            },
                            productFieldPasswordWarning,
                            productFieldOverrideServerOptions
                        ]
                    }
                ]
            }
        ]
    });
    
    //simpleForm.render(document.body);
    
    
// BOX: Trigger Server Plugin
    productFieldTriggerServerPluginCheckbox = new Ext.form.Checkbox({
        id:               'productFieldTriggerServerPluginCheckbox',
        name:             'productFieldTriggerServerPluginCheckbox',
        value:            false,
        validationEvent:  false,
        hideLabel:        true,
        boxLabel:         lang('Trigger Server Plugin'),
        hidden:           true
    });
    
    
// Window
    productWin = new Ext.Window({
        //el:           'productWindow',
        id:           "productWindow",
        y:            200,
        layout:       'fit',
        width:        480,
        autoHeight:   true,
        modal:        true,
        //closeAction:  'close',
        closable: false,
        title:        lang("Add Product"),
        plain:        true,
        shadow:       false,
        items:        [
            simpleForm
        ],
        buttons:      [
            productFieldTriggerServerPluginCheckbox,
            {
                id:       'btnAddProduct',
                text:     lang("Save"),
                hidden:   true,
                handler:  function(){
                    if(domainId != 0
                      && resetgenerateinvoice == 0){
                        AskAboutResettingRecurring();
                    }else{
                        sendProduct();
                    }
                }
            },
            {
                text:     'Close',
                handler:  function(){
                    productWin.hide();
                    productWin.destroy();
                }
            }
        ]
    });
    
    getCurrentProduct = function(action, id){
        var currentProduct = new Ext.data.JsonStore({
            root:           'productinfo',
            totalProperty:  'totalcount',
            idProperty:     'domainid',
            remoteSort:     true,
            baseParams:     {
                id: id
            },
            fields:         [
                'domainid',
                'packageStatus',
                'promotionid',
                'productid',
                'serverid',
                'serverplugin',
                'ipaddress',
                'sharedip',
                'domainname',
                'editdomain',
                'editserver',
                'domainusername',
                'domainpassword',
                'domainpasswordwarning',
                'datecreated',
                'hourcreated',
                'minutecreated',
                'secondcreated',
                'recurring',
                'billingcycle',
                'nextduedate',
                'priceoverride',
                'resetgenerateinvoice',
                'Buttons',
                'Boxes'
            ],
            proxy:          new Ext.data.HttpProxy({
                url: 'index.php?fuse=clients&action=Admin_GetClientDomain'
            })
        });
        
        currentProduct.on('load',function(){
            switch(action){
                case 'add':
                    productWin.setTitle(lang("Add Product"));
                    break;
                case 'edit':
                    productWin.setTitle(lang("Edit Product"));
                    break;
            }
            
            domainData = null;
            domainId = 0;
            editserver = true;
            packageStatus = null;
            altPrice = '0.00';
            resetgenerateinvoice = 0;
            fieldsContainer = {};
            addonsContainer = {};
            today = new Date();
            dateToday = today.dateFormat(gDateFormat);
            hourToday = (today.dateFormat('H')).toString();
            minuteToday = (today.dateFormat('i')).toString();
            secondToday = (today.dateFormat('s')).toString();
            
            if(currentProduct.data.length > 0){
                domainData = currentProduct.getAt(0).data;
            }
            
            var useSharedIp = true;
            var tempdomainname = '';
            var tempeditdomain = true;
            var tempdomainusername = '';
            var tempdomainpassword = '';
            var tempdomainpasswordwarning = 0;
            var tempdatecreated = dateToday;
            var temphourcreated = hourToday;
            var tempminutecreated = minuteToday;
            var tempsecondcreated = secondToday;
            var temprecurring = 1;
            var tempbillingcycle = 1;
            var tempnextduedate = dateToday;
            var temppriceoverride = '';
            var usepriceoverride = 0;
            
            if(domainData != undefined){
                if(validDomainData(domainData.domainpasswordwarning)){
                    tempdomainpasswordwarning = domainData.domainpasswordwarning;
                }
                
                if(validDomainData(domainData.resetgenerateinvoice)){
                    resetgenerateinvoice = domainData.resetgenerateinvoice;
                }
                
                if(validDomainData(domainData.Buttons)){
                    if(domainData.Buttons.savepackage == true){
                        Ext.getCmp('btnAddProduct').show();
                    }else{
                        Ext.getCmp('btnAddProduct').hide();
                    }
                }
                
                if(validDomainData(domainData.Boxes)){
                    if(domainData.Boxes.serverplugin == true){
                        productFieldTriggerServerPluginCheckbox.show();
                        productFieldTriggerServerPluginCheckbox.setValue(true);
                    }else{
                        productFieldTriggerServerPluginCheckbox.hide();
                        productFieldTriggerServerPluginCheckbox.setValue(false);
                    }
                }
                
                if(validDomainData(domainData.domainid)
                  && domainData.domainid != 0){
                    domainId = domainData.domainid;
                }else{
                    domainData = null;
                }
            }
            
            if(domainData != undefined){
                if(validDomainData(domainData.packageStatus)){
                    packageStatus = domainData.packageStatus;
                }
                
                if(domainData.sharedip != undefined
                  && domainData.sharedip != null){
                    useSharedIp = domainData.sharedip;
                }
                
                if(validDomainData(domainData.domainname)){
                    tempdomainname = domainData.domainname;
                }
                
                if(domainData.editdomain != undefined
                  && domainData.editdomain != null){
                    tempeditdomain = domainData.editdomain;
                }
                
                if(domainData.editserver != undefined
                  && domainData.editserver != null){
                    editserver = domainData.editserver;
                }
                
                if(validDomainData(domainData.domainusername)){
                    tempdomainusername = domainData.domainusername;
                }
                
                if(validDomainData(domainData.domainpassword)){
                    tempdomainpassword = domainData.domainpassword;
                }
                
                if(validDomainData(domainData.datecreated)){
                    //tempdatecreated = (new Date(Date.parse(domainData.datecreated))).dateFormat(gDateFormat);
                    tempdatecreated = domainData.datecreated;
                }
                
                if(validDomainData(domainData.hourcreated)){
                    temphourcreated = domainData.hourcreated;
                }
                
                if(validDomainData(domainData.minutecreated)){
                    tempminutecreated = domainData.minutecreated;
                }
                
                if(validDomainData(domainData.secondcreated)){
                    tempsecondcreated = domainData.secondcreated;
                }
                
                if(domainData.recurring != undefined
                  && domainData.recurring != null){
                      temprecurring = domainData.recurring;
                }
                
                if(validDomainData(domainData.billingcycle)){
                    tempbillingcycle = domainData.billingcycle;
                }
                
                if(validDomainData(domainData.nextduedate)){
                    //tempnextduedate = (new Date(Date.parse(domainData.nextduedate))).dateFormat(gDateFormat);
                    tempnextduedate = domainData.nextduedate;
                }
                
                if(validDomainData(domainData.priceoverride)){
                    temppriceoverride = domainData.priceoverride;
                }
            }
            
            productFieldSharedIp.setValue(useSharedIp);
            
            productFieldDomainName.setValue(tempdomainname);
            
            if(tempeditdomain && editserver){
                productFieldDomainName.enable();
            }else{
                productFieldDomainName.disable();
            }
            
            productFieldDomainName.editdomain = tempeditdomain;
            
            
            if(editserver){
                productFieldOverrideServerOptions.hide();
                
                productFieldSharedIp.enable();
                productFieldAvailableIps.enable();
                productFieldUserName.enable();
                productFieldPassword.enable();
            }else{
                productFieldOverrideServerOptions.show();
                
                productFieldSharedIp.disable();
                productFieldAvailableIps.disable();
                productFieldUserName.disable();
                productFieldPassword.disable();
            }
            
            productFieldUserName.setValue(tempdomainusername);
            productFieldPassword.setValue(tempdomainpassword);
            
            if(tempdomainpasswordwarning == 1){
                productFieldPasswordContainer.hide();
                productFieldPasswordWarning.show();
            }else{
                productFieldPasswordContainer.show();
                productFieldPasswordWarning.hide();
            }
            
            productFieldDateCreated.setValue(tempdatecreated);
            productFieldHourCreated.setValue(temphourcreated);
            productFieldMinuteCreated.setValue(tempminutecreated);
            productFieldSecondCreated.setValue(tempsecondcreated);
            
            if(temprecurring == 1){
                showProductFieldRecurringContainer();
            }else{
                hideProductFieldRecurringContainer();
            }
            
            productFieldRecurring.setValue(temprecurring);
            
            productFieldBillingCycle.setValue(tempbillingcycle);
            productFieldNextDueDate.setValue(tempnextduedate);
            productFieldNextDueDate.startingValue = tempnextduedate;
            
            if(temppriceoverride == ''){
                productFieldPriceOverride.disable();
            }else{
                altPrice = temppriceoverride;
                productFieldPriceOverride.enable();
                usepriceoverride = 1;
            }
            
            productFieldPriceOverride.setValue(temppriceoverride);
            productFieldPriceOverrideCheckbox.setValue(usepriceoverride);
            
            productGroupStore_OnLoad();
            
            Ext.getCmp('productTabPanels').activate('tabPanelBilling');
            
            productWin.show();
            
            //productFieldProductGroup.focus('',300); 
        });
        
        currentProduct.load();
    }
    
    function validDomainData(domainDataField)
    {
        if(domainDataField != undefined
          && domainDataField != null
          && domainDataField != ''){
            return true;
        }else{
            return false;
        }
    }
    
    // This function is for disabling and hidding a tab, and for selecting as active the first tab.
    function disableTab(tab_id)
    {
        var TabPanelsObject = Ext.getCmp('productTabPanels');
        var TabObject = TabPanelsObject.findById(tab_id);
        
        if(TabObject != undefined){
            if(TabPanelsObject.getActiveTab().id == tab_id){
                TabPanelsObject.activate('tabPanelBilling');
            }
            
            TabObject.disable();
            TabPanelsObject.hideTabStripItem(tab_id);
        }
    }
    
    AskAboutResettingRecurring = function(){
        var packageBillingChanged = false;
        
        if(domainData != undefined){
            if(domainData.promotionid != productFieldProductGroup.getValue()
              || domainData.productid != productFieldProduct.getValue()
              || domainData.recurring != productFieldRecurring.getValue()
              || domainData.billingcycle != productFieldBillingCycle.getValue()){
                packageBillingChanged = true;
            }
        }
        
        //ask if they want to reset recurring billing for this account
        //only need to ask if recurring is set to true or there are package addons
        if(packageBillingChanged
          &&(productFieldRecurring.getValue() == 1
          || productFieldAddonsContainer.items.length > 0)){
            Ext.Msg.show({
                title:    "Recreate recurring transaction?",
                msg:      "Click YES if you want to recreate the recurring transaction for this account. Click NO to just update this account and not reset invoice generation.\n\nNote: If you click YES you will need to delete the current recurring transaction at the 3rd party processor, since the next generated invoice will re-create one.",
                buttons:  Ext.Msg.YESNO,
                fn:       function(btn, text){
                    if(btn == 'yes'){
                        resetgenerateinvoice = 1;
                    }
                    
                    sendProduct();
                },
                icon:     Ext.MessageBox.QUESTION
            });
        }else{
            sendProduct();
        }
    }
    
    showProductWaitingMask = function(){
        productWaitingMask = new Ext.LoadMask('productWindow', {msg:"Please wait..."});
        
        productWaitingMask.show();
    }
    
    hideProductWaitingMask = function(){
        productWaitingMask.hide();
    }
}

function addProduct(){
    createProductWin();
    getCurrentProduct('add', 0);
}

function editProduct(id){
    createProductWin();
    getCurrentProduct('edit', id);
}

function sendProduct(){
    if(domainId == 0){
        var requestURL = 'index.php?fuse=clients&action=Admin_SaveNewDomain';
    }else{
        var requestURL = 'index.php?fuse=clients&action=Admin_UpdateDomain';
    }
    
    message = '';
    newline = "<br>";
    
    if(!productFieldProductGroup.validate()){
        if(message != ''){
            message += newline;
        }
        
        message += lang("Product Group");
    }
    
    if(!productFieldProduct.validate()){
        if(message != ''){
            message += newline;
        }
        
        message += lang("Product");
    }
    
    if(!(productFieldDateCreated.validate()
      && productFieldHourCreated.validate()
      && productFieldMinuteCreated.validate()
      && productFieldSecondCreated.validate())){
        if(message != ''){
            message += newline;
        }
        
        message += lang("Date Created");
    }
    
    if(!productFieldRecurring.validate()){
        if(message != ''){
            message += newline;
        }
        
        message += lang("Recurring");
    }else{
        if(productFieldRecurring.getValue() == 0){
            if(!productFieldBillingCycle.validate()){
                productFieldBillingCycle.setValue(1);
            }
        }else if(productFieldRecurring.getValue() == 1){
            if(!productFieldNextDueDate.validate()){
                if(message != ''){
                    message += newline;
                }
                
                message += lang("Next Due Date");
            }
        }
    }
    
    if(!productFieldBillingCycle.validate()){
        if(message != ''){
            message += newline;
        }
        
        message += lang("Billing Cycle");
    }
    
    if(productFieldPriceOverrideCheckbox.getValue() == true
      && !productFieldPriceOverrideValidate()){
        if(message != ''){
            message += newline;
        }
        
        message += lang("Price Override");
    }
    
    
    // GETTING CUSTOM FIELDS
    var customTags = '';
    var customFieldValues = '';
    
    // use Ip Address as a Custom Field
    var TabPanelsObject = Ext.getCmp('productTabPanels');
    var TabObject = TabPanelsObject.findById('tabPanelServer');
    
    if(TabObject != undefined
      && !TabObject.disabled){
        customTags += 'CT_1';
        
        customFieldValues += '&CT_1=' + encodeURIComponent(productFieldIpAddress.getValue());
        customFieldValues += '&CTT_1=0';
        
        if(!productFieldServer.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Server");
        }
        
        if(!productFieldIpAddress.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Ip Address");
        }
        
        if(!productFieldDomainName.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Domain Name");
        }
        
        if(!productFieldUserName.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("User Name");
        }
        
        if(!productFieldPassword.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Password");
        }
    }
    
    // the other customs fields
    for(var iterator = 0; iterator < productFieldFieldsContainer.items.length; iterator++){
        var currentFieldObject = productFieldFieldsContainer.getComponent(iterator);
        
        if(customTags != ''){
            customTags += ',';
        }
        
        customTags += currentFieldObject.id;
        
        if(currentFieldObject.dataType == '15'){
            //  typeDATE
            customFieldValues += '&' + currentFieldObject.id + '=' + encodeURIComponent(currentFieldObject.getRawValue());
        }else{
            customFieldValues += '&' + currentFieldObject.id + '=' + encodeURIComponent(currentFieldObject.getValue());
        }
        
        var currentFieldObjectIdArray = currentFieldObject.id.split("_");
        customFieldValues += '&CTT_' + currentFieldObjectIdArray[1] + '=' + encodeURIComponent(currentFieldObject.dataType);
        
        if(!currentFieldObject.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += currentFieldObject.fieldLabel;
        }
    }
    
    
    // GETTING ADDONS
    var addons_selected = '';
    
    for(var iterator = 0; iterator < productFieldAddonsContainer.items.length; iterator++){
        var currentAddonObject = productFieldAddonsContainer.getComponent(iterator);
        
        if(addons_selected != ''){
            addons_selected += ',';
        }
        
        addons_selected += currentAddonObject.getValue();
        
        if(!currentAddonObject.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += currentAddonObject.fieldLabel;
        }
    }
    
    if(message != ''){
        Ext.MessageBox.alert(lang("Errors"), lang("The following form field(s) were incomplete or incorrect") + ":<br><br>" + message + "<br><br>" + lang("Please complete or correct the form and submit again."));
        return;
    }else{
        if(domainId != 0){
            if(addons_selected != ''){
                if(productFieldNextDueDate.getRawValue() != productFieldNextDueDate.startingValue){
                    Ext.MessageBox.alert(lang("Notice"), lang('If you have some Addons applied to the package, their Next Due Date will not be updated. If you want to update them, please take a look on the Recurring section of the Customer Profile'));
                }
            }
        }
        
        showProductWaitingMask();
        
        new Ajax.Request(
            requestURL,
            {
                parameters: 'domainId='                + encodeURIComponent(domainId)
                         + '&DomainName='              + encodeURIComponent(productFieldDomainName.getValue())
                         + '&UserName='                + encodeURIComponent(productFieldUserName.getValue())
                         + '&Password='                + encodeURIComponent(productFieldPassword.getValue())
                         + '&validateServerOptions='   + encodeURIComponent(!Ext.getCmp('productTabPanels').findById('tabPanelServer').disabled)
                         + '&serverid='                + encodeURIComponent(productFieldServer.getValue())
                         + '&dateActivated='           + encodeURIComponent(productFieldDateCreated.getRawValue())
                         + '&hourActivated='           + encodeURIComponent(productFieldHourCreated.getValue())
                         + '&minuteActivated='         + encodeURIComponent(productFieldMinuteCreated.getValue())
                         + '&secondActivated='         + encodeURIComponent(productFieldSecondCreated.getValue())
                         + '&nextbilldate='            + encodeURIComponent(productFieldNextDueDate.getRawValue())
                         + '&shared='                  + encodeURIComponent(productFieldSharedIp.getValue())
                         + '&plan='                    + encodeURIComponent(productFieldProduct.getValue())
                         + '&paymentterm='             + encodeURIComponent(productFieldBillingCycle.getValue())
                         + '&promotionid='             + encodeURIComponent(productFieldProductGroup.getValue())
                         + '&price_override='          + encodeURIComponent(productFieldPriceOverrideCheckbox.getValue())
                         + '&price='                   + encodeURIComponent(productFieldPriceOverride.getValue())
                         + '&recurring='               + encodeURIComponent(productFieldRecurring.getValue())
                         + '&resetgenerateinvoice='    + encodeURIComponent(resetgenerateinvoice)
                         + '&serverplugin='            + encodeURIComponent(productFieldTriggerServerPluginCheckbox.getValue())
                         + '&addons_selected='         + encodeURIComponent(addons_selected)
                         + '&customTags='              + encodeURIComponent(customTags)
                         + customFieldValues,
                onComplete: onCompleteProductAction
            }
        );
    }
}

function onCompleteProductAction(responseObj){
    hideProductWaitingMask();
    var data = ce.parseAjaxResponse(responseObj);
    if(!data.error) {
        productWin.hide();
        productWin.destroy();
        //get the grid if there is one
        //if we are in the products view
        //if not then skip
        grid = Ext.getCmp("domains-grid");
        if(grid!=null){
            grid.getStore().load({params:{start:0}});
            //toggleButtons(0);
        }
        //we might want to check to see if we are showing a dropdown
        //in the event we are creating an invoice
        //do that code here and update the dropdown
    }
}