var ProductGroupWin;
var pgWin;
var emailsToNotify;

Ext.onReady(function(){

    function ProductGroupWindow(update){
        if(this instanceof ProductGroupWindow){
            //this.update = update;
            this.CreateWindow = createWindow;
            this.LoadFields = loadFields;
            this.SetForNewEntry = setForNewEntry;
        }else{
            return new TableTypeWindow();
        }
    }
    ProductGroupWin = new ProductGroupWindow();

    var welcomeEmailFieldSet;
    var detailsFieldSet;
    var domainFieldSet;
    var simpleForm;
    var nameField;
    
    //var nonstaffstore;

    function createWindow(update) {
        if (update) {
            //requesturl = 'index.php?fuse=support&action=SaveDepartment';
            buttonText = lang('Update');
            titleText = '&nbsp;&nbsp;'+lang('Edit Department');
        } else {
            //requesturl = 'index.php?fuse=support&action=SaveDepartment';
            buttonText = lang('Add');
            titleText = '&nbsp;&nbsp;'+lang('Add Department');
        }

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

        
        
        departmentstore = new Ext.data.JsonStore({
            id:             "departmentstore",
            root:           'groups', //'departments',
            totalProperty:  'totalcount',
            idProperty:     'id',
            remoteSort:     true,
            baseParams:     {
                                filter: "",
                                customerid: "0"
                            },
            fields:         [
                                'id',
                                'groupname'
                            ],
            proxy:          new Ext.data.HttpProxy({
                                url:  'index.php?fuse=admin&action=GetAccessGroupList&staffonly=1'
                            })
        });


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

        nonstaffstore = new Ext.data.JsonStore({
            id:             "nonstaffstore",
            root:           'nonstafflist', //'departments',
            //totalProperty:  'totalcount',
            idProperty:     'nonstaffId',
            remoteSort:     true,
            fields:         [
                                'nonstaffId',
                                'nonstaffLabel'
                            ]
        });

        lc = new Ext.ux.form.LovCombo({
             id:'lovcombo'
            ,anchor:'70%'
            ,fieldLabel: lang('Staff Group Members')
            ,hideOnSelect:false
            ,editable:false
            ,maxHeight:200
            ,store:departmentstore
            ,displayField:'groupname'
            ,valueField:'id'
            ,triggerAction:'all'
            ,mode:'local'
            ,x:130
            
            ,beforeBlur : Ext.emptyFn
        });

        addToDepartment = new Ext.ux.form.LovCombo({
             id:'addToDepartmentlovcombo'
            ,anchor:'70%'
            ,hideOnSelect :false
            ,editable :false
            ,maxHeight:200
            ,store:nonstaffstore
            ,displayField:'nonstaffLabel'
            ,valueField:'nonstaffId'
            ,triggerAction:'all'
            ,mode:'local'
            ,x:130
            ,beforeBlur : Ext.emptyFn
        });

        addDeptButton = new Ext.Button({
                     id:'addDeptButton',
                     height:15,
                      x: 380,
                      y: 0,
                     text:lang('Add'),
                     width:50
                 })

        var Staff = Ext.data.Record.create([{
            name: 'name',
            type: 'string'
        },{
            name: 'active',
            type: 'bool'
        }]);

        var isEditable = true;
        var hinderSelection = false; // Create the flag

        var editor = new Ext.ux.grid.RowEditor({
            saveText: 'Update',
            listeners : {
                'beforeedit' :function(roweditor,rowIndex){
                    
                    if(!isEditable){
                        isEditable = true;
                        return false;
                    }
                }
            }
        });

        depstaff_store = new Ext.data.JsonStore({
            id: "depstaff_store",
            root: 'staff',
            idProperty: 'staffId',
            remoteSort: true,
            fields: [
                'name','userid','leadSelected', 'checkAssignTo', 'checkNotifyTo', 'checkClosed', 'checkFeedback', 'checkResolution'
            ]
        });

        depstaff_store.setDefaultSort('userid', 'asc');

        
        var sm1 = new Ext.grid.CheckboxSelectionModel({

        listeners:{
            'beforerowselect' : function (sm1, rowIndex, keep, rec) {
                
                if(hinderSelection) {
                        hinderSelection = false;
                        return false;
                    }
              },
             'rowdeselect': function(model, rowIndex, record){
                    isEditable = false;
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                  
                    isEditable = false;
                    toggleButtons();
              }
            }
        });
        function toggleButtons(record, count){
            
            if(count == undefined){
                count = sm1.getCount();
            }
            if(count > 0){
                deletebutton.setDisabled(false);
            }else{
                deletebutton.setDisabled(true);
            }
        }

        var helpEmails = lang('Enter one E-mail per line.') + '<br />' + lang('E-mail addresses to CC notification messages for new high priority tickets');

        emailsToNotify = new Ext.form.TextArea({
            id:               'emailsToNotify',
            name:             'emailsToNotify',
            //fieldLabel:       lang("E-mails") + " <img class='tip-target' src='../templates/admin/images/information-button.png' qtip='" + helpEmails.replace(/'/g, "&#39;") + "'/>",
            fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpEmails.replace(/'/g, "&#39;") + "'>" + lang(" E-mail For New High Priority Support Tickets") + "</span>",
            border:           false,
            validationEvent:  false,
            width:            200,
            height:           100,
            value:            ''
        });

        depstaffgrid = new Ext.grid.GridPanel({
                store: depstaff_store,
                width: 600,
                id: 'depstaff_grid',
                autoExpandColumn: 'name',
                plugins: [editor],
                columns: [
                    sm1,
                    {
                        id: 'name',
                        header: 'First Name',
                        dataIndex: 'name',
                        width: 99,
                        menuDisabled:true
                    },{
                        xtype: 'booleancolumn',
                        header: 'Lead',
                        dataIndex: 'leadSelected',
                        align: 'center',
                        menuDisabled:true,
                        width: 37,
                        trueText: 'Yes',
                        falseText: 'No',
                        editor: {
                            xtype: 'checkbox'
                        }
                    },{
                        xtype: 'booleancolumn',
                        header: 'Assign',
                        dataIndex: 'checkAssignTo',
                        align: 'center',
                        width: 47,
                        menuDisabled:true,
                        trueText: 'Yes',
                        falseText: 'No',
                        editor: {
                            xtype: 'checkbox'
                        }
                    },{
                        xtype: 'booleancolumn',
                        header: 'Notify',
                        dataIndex: 'checkNotifyTo',
                        align: 'center',
                        width: 44,
                        trueText: 'Yes',
                        falseText: 'No',
                        menuDisabled:true,
                        editor: {
                            xtype: 'checkbox'
                        }
                    },{
                        xtype: 'booleancolumn',
                        header: 'Closed',
                        dataIndex: 'checkClosed',
                        align: 'center',
                        width: 47,
                        trueText: 'Yes',
                        falseText: 'No',
                        menuDisabled:true,
                        editor: {
                            xtype: 'checkbox'
                        }
                    },{
                        xtype: 'booleancolumn',
                        header: 'Feedback',
                        dataIndex: 'checkFeedback',
                        align: 'center',
                        width: 60,
                        trueText: 'Yes',
                        falseText: 'No',
                        menuDisabled:true,
                        editor: {
                            xtype: 'checkbox'
                        }
                    },{
                        xtype: 'booleancolumn',
                        header: 'Resolution',
                        dataIndex: 'checkResolution',
                        align: 'center',
                        width: 69,
                        trueText: 'Yes',
                        falseText: 'No',
                        menuDisabled:true,
                        editor: {
                            xtype: 'checkbox'
                        }
                    }

                ],sm: sm1,
                buttons:[deletebutton = new Ext.Button({
                     id:'deletebutton',
                     autoHeight:true,
                     arrowAlign:'right',
                     xtype:'splitbutton',
                     text:lang('Delete'),
                     disabled: true
                 }),],
                buttonAlign:'left',
                listeners: {
                    rowmousedown: function() {
                        hinderSelection = true;
                    }
                }
            });

            var btnButtonActionHandler = function(button, event){
                requesturl = "index.php?fuse=support&action=DeleteStaff";
                var confirmmsg = lang("Do you want to delete the selected staff(s)? (Ok=YES , Cancel=No)");
                if(!confirm(confirmmsg)){
                    return true;
                }
                var departmentId = simpleForm.findById("id").getValue();
                Ext.Ajax.request({
                   url: requesturl,
                   success: function(xhr) {
                        //refreshgrid
                        depstaffgrid.getView().refresh(true);
                        win.enable();
                        gridstore.load();
                        loadFields(departmentId);
                        toggleButtons(0, 0);
                        var data = Ext.util.JSON.decode(xhr.responseText);
                        if(data.error){
                            //we do not need to repopulate the filters if there was a validation error
                           msg(lang("There was an error performing this action"),"");
                        }else if(data.message){
                            msg(data.message,"");
                        }
                   },
                   failure: function() {
                        depstaffgrid.enable()
                        Ext.Msg.alert("Fail");
                   },
                   params: {
                       departmentId : departmentId,
                       memberIds : Ext.util.JSON.encode(getMemberIds())
                   }
                });
            }

            var addDeptButtonActionHandler = function(button, event){
                requesturl = "index.php?fuse=support&action=AddStaff";
                var departmentId = simpleForm.findById("id").getValue();
                if(addToDepartment.getValue() == ""){
                    alert("Please select a staff to add");
                    return false;
                }
                var addToDeptArr = addToDepartment.getValue().split(",");
                
                Ext.Ajax.request({
                   url: requesturl,
                   success: function(xhr) {
                        depstaffgrid.getView().refresh(true);
                        win.enable();
                        gridstore.load();
                        loadFields(departmentId);
                        toggleButtons(0, 0);
                        var data = Ext.util.JSON.decode(xhr.responseText);
                        if(data.error){
                            //we do not need to repopulate the filters if there was a validation error
                           msg(lang("There was an error performing this action"),"");
                        }else if(data.message){
                            msg(data.message,"");
                        }
                   },
                   failure: function() {
                        staffgrid.enable()
                        Ext.Msg.alert("Fail");
                   },
                   params: {
                       departmentId : departmentId,
                       addToDepartment : Ext.util.JSON.encode(addToDeptArr)
                   }
                });
            }

            function addButtonListeners(){
                deletebutton.addListener("click",btnButtonActionHandler);
                addDeptButton.addListener("click",addDeptButtonActionHandler)
            }
            function getMemberIds(){
                var arrayofids = new Array();
                rows = sm1.getSelections();
                for(x=0;x<rows.length;x++){
                    arrayofids[x] = rows[x].data.userid;
                }
                return arrayofids;
            }
            addButtonListeners();

            welcomeEmailFieldSet = new Ext.form.FieldSet({
            anchor: '100%',
            items: [{
                xtype: 'tabpanel',
                activeTab: 0,
                height: 250,
                defaults:       {bodyStyle:'padding:10px; background-color:WhiteSmoke'},
                plain: true,
                items:[{
                    cls: 'x-plain',
                    title: lang('Staff'),
                    layout:'fit',
                    items:[depstaffgrid]
                },{
                    cls: 'x-plain',
                    title: lang('Settings'),
                    layout:'fit',
                    //items:[emailsToNotify]
                    items:[
                            {
                              columnWidth:  1,
                              layout:       'form',
                              border:       false,
                              items:        [
                                                emailsToNotify
                                            ]
                            }

                    ]
                }

                ]
            }]
        });
        
        detailsFieldSet = [{
            id:'id',
            name: 'id',
            value: '0',
            xtype: "hidden",
            hidden:true
        }
        ];

        nameItems = [{
                        layout: "absolute",
                            height: 40,
                            items: [
                                    {
                                        xtype: "label",
                                        text: "Name:",
                                        x: 5,
                                        y:3
                                    },
                                    {
                                        //fieldLabel: lang('Name'),
                                        id:'name',
                                        name: 'name',
                                        xtype: "textfield",
                                        x: 130,
                                        
                                        allowBlank:false,
                                        anchor:'70%'
                                    },
                                   ]
        }];
        staffGroupItems = [{
                            layout: "absolute",
                            height: 40,
                            items: [{

                                        xtype: "label",
                                        text: "Staff Group Members:",
                                        x: 5,
                                        y:3
                            },lc
                            ]
                            }];
        addToDeptItems = [{
                            layout: "absolute",
                            height: 40,
                            items: [{
                                        xtype: "label",
                                        text: "Non staff Members:",
                                        x: 5,
                                        y:3
                                    },
                                    addToDepartment,
                                    addDeptButton
                                    ]
                         }
                ];




        simpleForm = new Ext.FormPanel({
            labelAlign: 'top',
            frame:true,
            hideBorders:true,
            shadow:false,
            floating:false,
            autoHeight:true,
            title: '',
            bodyStyle:'padding:5px 5px 0',
            width: 550,
            items: [ detailsFieldSet,
                     nameItems,
                     staffGroupItems,
                     addToDeptItems
                , welcomeEmailFieldSet ]
        });

        win = new Ext.Window({
            layout:'fit',
            title:titleText,
            width:550,
            y:25,
            shadow:false,
            autoHeight:true,
            modal:true,
            closeAction:'hide',
            plain: true,
            items: [simpleForm],
            fbar: [
                    {
                        text: lang('Close'),
                        handler: function(){
                            win.hide();
                        }
                    },
                    {
                        text: buttonText,
                        handler: function(){
                                var groupMemArr = null;
                                var addToDeptArr = null;
                                if(lc.getValue()!=""){
                                    groupMemArr = Ext.util.JSON.encode(lc.getValue().split(","));
                                }
                                if(buttonText != lang("Update")){
                                    if(addToDepartment.getValue()!=""){
                                        addToDeptArr = Ext.util.JSON.encode(addToDepartment.getValue().split(","));
                                    }
                                }
                                //alert("update");
                                //var mails = emailsToNotify.getValue().split("\n");
                                var mails = emailsToNotify.getValue().replace("\n",",");
                                /*for(x=0;x<mails.length;x++){
                                    alert(mails[x]);
                                }*/
                                simpleForm.getForm().submit({
                                clientValidation: true,
                                url: 'index.php?fuse=support&action=SaveDepartment',
                                params: {
                                    departmentId : simpleForm.findById("id").getValue(),
                                    name : simpleForm.findById("name").getValue(),
                                    departmentGroups : groupMemArr,
                                    addToDepartment : addToDeptArr,
                                    departmentAdmins : getRowIds(),
                                    departmentLead : getLeadId(),
                                    assign_to : Ext.util.JSON.encode(getAssignIds()),
                                    notify_to : Ext.util.JSON.encode(getNotifyIds()),
                                    sendclosed: Ext.util.JSON.encode(getClosedIds()),
                                    sendfeedback:Ext.util.JSON.encode(getFeedbackIds()),
                                    sendresolution:Ext.util.JSON.encode(getResolutionIds()),
                                    mailsToNotify:Ext.util.JSON.encode(mails)
                                },
                                success: function(form, action) {
                                   win.hide();
                                   gridstore.load();
                                },
                                failure: function(form, action) {
                                    switch (action.failureType) {
                                        case Ext.form.Action.CLIENT_INVALID:
                                            Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                                            break;
                                        case Ext.form.Action.CONNECT_FAILURE:
                                            Ext.Msg.alert('Failure', 'Ajax communication failed');
                                            break;
                                        case Ext.form.Action.SERVER_INVALID:
                                            Ext.Msg.alert('Failure', action.result.msg);
                                   }
                                }
                            });
                        }
                    }
            ],
            listeners: {
                hide: function() { simpleForm.destroy(); }
            }
        });

        //simpleForm.getForm().reset();
        win.show(this);
    }

    function getRowIds(){
        var arrayofids = null;
        if(depstaff_store.getCount()>0){
            arrayofids = new Array();
        }
        for(x=0;x<depstaff_store.getCount();x++){
            arrayofids[x] = depstaff_store.getAt(x).get('userid');
        }
        /*if(addToDepartment.getValue()!=""){
            if(arrayofids == null)arrayofids = new Array();
            if(addToDepartment.getValue())
            arrayofids.push(addToDepartment.getValue().split(","));
        }*/
        if(arrayofids == null){
           return arrayofids;
        }else{
            
            return Ext.util.JSON.encode(arrayofids);
        }
	    
    }

    function getLeadIds(){
        var arrayofids = new Array();
        var i=0;
        for(x=0;x<depstaff_store.getCount();x++){
            if(depstaff_store.getAt(x).get('leadSelected')==true){
                arrayofids[i] = depstaff_store.getAt(x).get('userid');
                i++;
            }
        }
       
	    return arrayofids;
    }

    function getLeadId(){
        for(x=0;x<depstaff_store.getCount();x++){
            if(depstaff_store.getAt(x).get('leadSelected')==true){
                return depstaff_store.getAt(x).get('userid');
                
            }
        }
    }

    function getAssignIds(){
        var arrayofids = new Array();
        var i=0;
        for(x=0;x<depstaff_store.getCount();x++){
            if(depstaff_store.getAt(x).get('checkAssignTo')==true){
                arrayofids[x] = depstaff_store.getAt(x).get('userid');
                i++;
            }
        }
	    return arrayofids;
    }

    function getNotifyIds(){
        var arrayofids = new Array();
        var i=0;
        for(x=0;x<depstaff_store.getCount();x++){
            if(depstaff_store.getAt(x).get('checkNotifyTo')==true){
                arrayofids[x] = depstaff_store.getAt(x).get('userid');
                i++;
            }
        }
	    return arrayofids;
    }

    function getClosedIds(){
        var arrayofids = new Array();
        var i=0;
        for(x=0;x<depstaff_store.getCount();x++){
            if(depstaff_store.getAt(x).get('checkClosed')==true){
                arrayofids[x] = depstaff_store.getAt(x).get('userid');
                i++;
            }
        }
	    return arrayofids;
    }

    function getFeedbackIds(){
        var arrayofids = new Array();
        var i=0;
        for(x=0;x<depstaff_store.getCount();x++){
            if(depstaff_store.getAt(x).get('checkFeedback')==true){
                arrayofids[x] = depstaff_store.getAt(x).get('userid');
                i++;
            }
        }
	    return arrayofids;
    }

    function getResolutionIds(){
        var arrayofids = new Array();
        var i=0;
        for(x=0;x<depstaff_store.getCount();x++){
            if(depstaff_store.getAt(x).get('checkResolution')==true){
                arrayofids[x] = depstaff_store.getAt(x).get('userid');
                i++;
            }
        }
	    return arrayofids;
    }

    function setAdminDatas(adminsdatalist){
        for(x=0;x<depstaff_store.getCount();x++){
            depstaff_store.getAt(x).set('leadSelected',adminsdatalist[x]['leadSelected']);
            depstaff_store.getAt(x).set('checkAssignTo',adminsdatalist[x]['checkAssignTo']);
            depstaff_store.getAt(x).set('checkNotifyTo',adminsdatalist[x]['checkNotifyTo']);
            depstaff_store.getAt(x).set('checkClosed',adminsdatalist[x]['checkClosed']);
            depstaff_store.getAt(x).set('checkFeedback',adminsdatalist[x]['checkFeedback']);
            depstaff_store.getAt(x).set('checkResolution',adminsdatalist[x]['checkResolution']);
        }
    }

    function loadFields(id){
        simpleForm.getForm().load({
            url: 'index.php?fuse=support&action=Admin_GetDepartment',
            waitMsg:lang('Loading'),
            params: {department : id},
            success: function(form, action) {
                // special loading rules
                var response = Ext.util.JSON.decode(action.response.responseText);
                simpleForm.findById("id").setValue(id);
                simpleForm.findById("name").setValue(response.data.departmentName);
                var mailsToDisplay = "";
                if(response.data.mailsToNotify != null){
                    mailsToDisplay = response.data.mailsToNotify.replace(",","\n");
                }
                simpleForm.findById("emailsToNotify").setValue(mailsToDisplay);
                lc.setValue(response.data.accessgroupids);
                nonstaffstore.loadData(response.data);
                depstaff_store.loadData(response.data);
                setAdminDatas(response.data.staff);
            },
            failure: function(form, action) {alert('failure');}
            
        });

    }

    function setForNewEntry(){
        
    }
    


});


function editDepartment(id)
{
    ProductGroupWin.CreateWindow(true);
    ProductGroupWin.LoadFields(id);
}

function addDepartment()
{
    ProductGroupWin.CreateWindow(false);
    ProductGroupWin.SetForNewEntry();
    ProductGroupWin.LoadFields(null);
    addDeptButton.disable();
}