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


var groupWin;
var groupName;
var livechatcb;
var groupDesc;
var groupColor;
var useDefault;
var cp;
var simpleForm;
var addButton;
var deleteButton;
var color;
var livechatstore;
var editGroupWindowId=0;

Ext.onReady(function(){

    groupDisplayField = new Ext.form.DisplayField({
        id:         'groupDisplayField',
        name:       'groupDisplayField',
        value:      lang("Add your new customer group in the fields below."),
        hideLabel:  true,
        style: 'text-align:center;padding-bottom:8px',
        border:     false,
        anchor:     '100%'
    });
    groupId = new Ext.form.Hidden({
        id:         'id',
        name:       'id'

    });
    groupName = new Ext.form.TextField({
        id:         'groupname',
        name:       'groupname',
        fieldLabel: lang("Name"),
        labelStyle: 'font-weight:bold;font-size:11px;',
        border:     false,
        anchor:     '100%',
        allowBlank: false,
        blankText:  lang("This field is required")
    });

    groupDesc = new Ext.form.TextArea({
        id:         'description',
        name:       'description',
        fieldLabel: lang("Description"),
        labelStyle: 'font-weight:bold;font-size:11px;',
        border:     false,
        anchor:     '100%'
        
    });
    groupColor =  new Ext.form.TextField({
        id:         'groupColor',
        name:       'groupColor',
        fieldLabel: lang("Hex value"),
        labelStyle: 'font-weight:bold;font-size:11px;',
        border:     false,
        anchor:     '100%',
        hidden:false
       // hideLabel:true
    });
    cp = new Ext.ColorPalette({
        id: 'colorPal',
        name: 'colorPal',
        hidden: true,
        border:false,
        style:"text-align:right"
       // fieldLabel:"Select color"
    });  // initial selected color
    cp.on('select', function(palette, selColor){
        // do something with selColor
        groupColor.setValue("#"+selColor);
    });
    useDefault = new Ext.form.Checkbox({
        id:         'useDefault',
        name:       'useDefault',
        labelStyle: 'font-weight:bold;font-size:11px;',
       // border:     false,
        fieldLabel: lang("Group Color"),
        boxLabel:   lang("use default"),
        checked:    true,
        listeners:{check:function(){
                if(useDefault.checked == false){
                    groupColor.setVisible(true);
                    groupColor.hideLabel = false;
                    groupColor.getEl().up('.x-form-item').setDisplayed(true);
                    cp.setVisible(true);
                }else{
                    groupColor.setVisible(false);
                    cp.setVisible(false);
                    groupColor.getEl().up('.x-form-item').setDisplayed(false);
                    groupColor.hideLabel = true;
                }
        }}
    });

    addButton = new Ext.Button({
                              id:       'btnAddGroup',
                              text:     lang("Add Group"),
                              disabled: false,
                              hidden:   false,
                              handler:  function(){
                                            sendGroup();
                              }
                          });
    deleteButton = new Ext.Button({
                              id:       'btnDeleteGroup',
                              text:     lang("Delete Group"),
                              disabled: false,
                              hidden:   false,
                              handler:  function(){
                                            deleteGroup();
                              }
                          });
   
    livechatstore = new Ext.data.JsonStore({
        id:             "livechatstore",
        root:           'plugins',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        fields:         [
                            'id',
                            'name'
                        ],
        proxy:          new Ext.data.HttpProxy({
                            url:  'index.php?fuse=admin&action=adminGetLiveSupportPlugins&enabled=1'
                        })
    });
    livechatstore.on("load", function(){
        //if we are editing then lets populate the window after this store to ensure we have the data
        if (editGroupWindowId!=0) {
            groupWin.setTitle("Edit Group");
            addButton.setText("Update Group");
            groupDisplayField.setValue("Edit your customer group in the fields below.");
            deleteButton.show();
            groupWin.show();
            groupColor.getEl().up('.x-form-item').setDisplayed(false);
            populateFields(editGroupWindowId);
        }
    });

    livechatcb = new Ext.form.ComboBox({
        id:         'cbLiveSupport',
        name:       'cbLiveSupport',
        triggerAction:    'all',
        lazyRender:       true,
        editable:         false,
        mode:             'local',
        store:      livechatstore,
        valueField: 'id',
        displayField: 'name',
        fieldLabel: lang("Live Support"),
        labelStyle: 'font-weight:bold;font-size:11px;',
        border:     false,
        anchor:     '100%'
    });

    simpleForm = new Ext.FormPanel({
        //labelWidth: 75, // label settings here cascade unless overridden
        frame:true,
        border:false,
        hideBorders:true,
        bodyStyle:'padding:8px 15px 0',
        defaultType: 'textfield',

        items: [groupDisplayField,
                          groupId,
                          groupName,
                          groupDesc,
                          livechatcb,
                          useDefault,
                          groupColor,
                          cp
        ]
        
    });
    
    groupWin = new Ext.Window({
        id:           "groupWindow",
        x:            400,
        y:            200,
        labelAlign:   'right',
        layout:       'form',
        width:        400,
        modal: true,
        autoHeight:   true,
        defaultType:  'textfield',
        shadow:false,
        closeAction:  'hide',
        title:        lang("Add Group:"),
        plain:        true,
        closable:     true,
        buttonAlign:  'right',
        items:        [
                          simpleForm
                      ],
        buttons:      [
                         addButton,
                         deleteButton
                      ]
    });

});

function addGroup(){
    editGroupWindowId = 0;
    livechatstore.load();
    groupId.reset();
    groupId.setValue("0");
    groupName.reset();
    groupDesc.reset();
    useDefault.setValue(true);
    groupColor.setVisible(false);
    
    groupColor.hide();
    groupWin.setTitle("Add Group");
    addButton.setText("Add Group");
    deleteButton.hide();

    groupWin.show();

    groupColor.getEl().up('.x-form-item').setDisplayed(false);
    groupName.focus('',300);

}

function editGroup(id){
    editGroupWindowId = id;
    livechatstore.load();
}

function populateFields(id) {
    geturl = 'index.php?fuse=admin&action=GetCustomerGroupList&id=' + id;
    simpleForm.getForm().load({url:geturl, waitMsg:'Loading'});
}

function deleteGroup() {
	Ext.Ajax.request({
		url:      "index.php?fuse=admin&action=DeleteCustomerGroup",
		success:  function(xhr) {
			//onCompleteSendGroup(xhr);
            json = ce.parseAjaxResponse(xhr);
            if (!json.error) {
                groupWin.hide();
                gridstore.reload();
            }
		},
		params:   { groupId:  groupId.getValue() }
	});
}

function sendGroup() {
    
    if (groupName.validate()) {
        useDefaultVar = "";
        groupColorVar = "";
        if(groupColor.getValue() != ""){
            groupColorArr = groupColor.getValue().split("#",2);
            groupColorVar = groupColorArr[1];
        }

        if(useDefault.getValue()){
            useDefaultVar = "1";
        }else{
            useDefaultVar = '0';
        }

        Ext.Ajax.request({
            url:      "index.php?fuse=admin&action=SaveCustomerGroup",
            success:  function(xhr) {
                //onCompleteSendGroup(xhr);
                json = ce.parseAjaxResponse(xhr);
                if (!json.error) {
                    groupWin.hide();
                    gridstore.reload();
                }
            },
            params:   {
                isAddGroup: '1',
                groupId:	groupId.getValue(),
                groupName:	groupName.getValue(),
                groupDescription:	groupDesc.getValue(),
                useDefault:	useDefaultVar,
                livesupportid : livechatcb.getValue(),
                groupColor:	groupColorVar
            }
        });
    } else {
        message = '';
        newline = "<br>";
        if(!groupName.validate()){
            if(message != ''){
                message += newline;
            }
            message += lang("Name")
        }

        if(!groupDesc.validate()){
            if(message != ''){
                message += newline;
            }
            message += lang("Description")
        }

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