var defaultWidth = 250;
var announcementWaitingMask;

var gridstore;
var simpleForm;
var announcementWin;
var announcementId;
var announcementTitle;
var announcementPostDate;
var announcementExcerpt;
var announcementPost;
var announcementPostTime;
var announcementPostValidate;
var announcementPublish;
var announcementEmail;
var announcementOverrideOptOut;
var announcementRecipients;
var announcementStatusTarget;
var announcementStatusTargetValidate;
var announcementStatusTargetContainer;
//var announcementUserTarget;
//var announcementUserTargetValidate;
//var announcementUserTargetContainer;
var announcementServerTarget;
var announcementServerTargetValidate;
var announcementServerTargetContainer;
var announcementPackageTarget;
var announcementPackageTargetValidate;
var announcementPackageTargetContainer;

Ext.onReady(function(){


/*
 * Class for saving grid state. Modeled on LayoutStateManager
 */

Ext.grid.GridStateManager = function(){
     // default empty state
     this.state = {
        hidden: { },
        locked: { },
        widths: { }
    };
};

Ext.grid.GridStateManager.prototype = {
    init : function(grid, provider){
        this.provider = provider;
        this.grid = grid;
        var state = columnsavedstate;

        if(state) {
            state.hidden = state.hidden || { };
            for (var colId in state.hidden) {
              var colIndex = this.grid.getColumnModel().getIndexById(colId);
              if (!isNaN(colIndex) && colIndex >= 0) {
                this.grid.getColumnModel().setHidden(colIndex, state.hidden[colId]);
              }
            }
            state.locked = state.locked || { };
            for (var colId in state.locked) {
              var colIndex = this.grid.getColumnModel().getIndexById(colId);
              if (!isNaN(colIndex) && colIndex >= 0) {
                this.grid.getColumnModel().setLocked(colIndex, state.locked[colId]);
              }
            }
            state.widths = state.widths || { };
            for (var colId in state.widths) {
              var colIndex = this.grid.getColumnModel().getIndexById(colId);
              if (!isNaN(colIndex) && colIndex >= 0) {
                this.grid.getColumnModel().setColumnWidth(colIndex, state.widths[colId]);
              }
            }
            if (state.sortInfo) {
              //this.grid.getDataSource().setDefaultSort(state.sortInfo.field, state.sortInfo.direction);
            }
            if (state.colIds) {
              for (var i = 0; i < state.colIds.length; i++) {
                var savedColId = state.colIds[i];
                var initialColIndex = this.grid.getColumnModel().getIndexById(savedColId);
                if (!isNaN(initialColIndex) && initialColIndex > 0 && initialColIndex != i) {
                  this.grid.getColumnModel().moveColumn(initialColIndex, i);
                }
              }
            }
            this.state = state;
        }
        grid.getColumnModel().on("hiddenchange", this.onHiddenChange, this);
        // for some reason the widthchange event on ColumnModel always gives width = undefined
        // so have to list to the event on the grid directly
        grid.on("columnresize", this.onColumnResize, this);
        grid.getColumnModel().on("columnlockchange", this.onLockChange, this);
        grid.getColumnModel().on("columnmoved", this.onColumnMove, this);
        //grid.getDataSource().on("datachanged", this.onSort, this);
    },

    getStateKey : function() {
      return this.grid.id + "-grid-state";
    },

    storeState : function(){

        // Upadat the local var
        columnsavedstate = this.state;

        // Post it
        Ext.Ajax.request({
           url: 'index.php?fuse=admin&action=updateGridSavedState',
           success: function(xhr) {
                    },
           failure: function() {
                NE_log(1,"Failed from saving gridstate");
           },
           params: { gridcustomfield: 'AnnouncementGridState',
                     gridsavedstate: Ext.encode(gridsavedstate),
                     columnsavedstate: Ext.util.JSON.encode(this.state)
                     },
           method:'post'
        });
    },

    onHiddenChange : function(cm, colIndex, hidden){
        var colId = cm.getColumnId(colIndex);
        this.state.hidden[colId] = hidden;
        this.storeState();
    },

    onColumnResize : function(colIndex, width){
        var colId = this.grid.getColumnModel().getColumnId(colIndex);
        this.state.widths[colId] = width;
        this.storeState();
    },

    onLockChange : function(cm, colIndex, lockState){
        var colId = cm.getColumnId(colIndex);
        this.state.locked[colId] = lockState;
        this.storeState();
    },

    onColumnMove : function(cm, oldIndex, newIndex){
        // we do this one by saving array of current order of column ids
        var colIds = [];
        for(var i = 0; i < cm.getColumnCount(); i++){
            colIds.push(cm.getColumnId(i));
        }
        this.state.colIds = colIds;
        this.storeState();
    },

    onSort : function(dataSource){
        if (dataSource.sortInfo) {
          this.state.sortInfo = { field: dataSource.sortInfo.field, direction: dataSource.sortInfo.direction }
          this.storeState();
        }
    }
};

/*
 * @enhancements
 * Add method to Grid to restore state.
 */
Ext.apply(Ext.grid.GridPanel.prototype, {
  restoreState: function (provider) {
    if (!provider) {
      provider = Ext.state.Manager;
    }
    var sm = new Ext.grid.GridStateManager();
    sm.init(this, provider);
  }
});


    if(document.getElementById('addannouncementbtn') != null){
        new Ext.Button({
            id:         "addannouncement",
            renderTo:   "addannouncementbtn",
            text:       lang('Add Announcement'),
            iconAlign:  'left',
            handler:    function(){
                createAnnouncementWin();
            }
        });
    }
    
    gridstore = new Ext.data.JsonStore({
        id:             "gridstore",
        root:           'announcements',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        fields:         [
            'id',
            'title',
            'published',
            'postdate'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=admin&action=AdminGetAnnouncements'
        })
    });
    
    gridstore.setDefaultSort(gridsavedstate.sortinfo.field, gridsavedstate.sortinfo.dir);
    gridstore.setBaseParam('limit', gridsavedstate.displaysize);
    
    var announcementgridbb = new Ext.PagingToolbar({
        id:         'announcemnetgridpagingbar',
        store:      gridstore,
        pageSize:   gridsavedstate.displaysize,
        listeners:  {
            'change': function(bb, data){

			if(data.total == 0) { var addBy = 0;} else { var addBy = 1;}
			from = (data.activePage * bb.pageSize) - bb.pageSize + addBy;
			to = from+ bb.pageSize - 1;
			if(to>data.total) to = data.total;

			document.getElementById('announcemnetgridpagingbar').style.display = ( data.pages > 1 ) ? '' : 'none';
                
                document.getElementById('announcementslistlabel').innerHTML = String.format(lang('Displaying announcements') + ' {0} - {1}' + ' of ' + '{2}', from, to, data.total);
            }
        }
    });
    
    function renderTitle(value, p, record)
    {
        var returnValue = "";
        
        if(record.data.published == "0"){
            returnValue = "<span style='color:gray;font-style:italic;'>" + record.data.title + "</span>";
        }else{
            returnValue = record.data.title;
        }
        
        //add to url link
        returnValue = "<a href='#' onclick='emailCustomer(" + record.data.id + ");'>" + returnValue + "</a>";
        
        return returnValue;
    }
    
    function renderPublished(value, p, record)
    {
        if(record.data.published == "0"){
            return lang("No");
        }else{
            return lang("Yes");
        }
    }
    
    var sm = new Ext.grid.CheckboxSelectionModel({
        listeners:  {
            'rowdeselect':  function(model, rowIndex, record){
                toggleButtons(record);
            },
            'rowselect':    function(model, rowIndex, record){
                toggleButtons(record);
            }
        }
    });
    
    function toggleButtons(record, count)
    {
        if(count == undefined){
            count = sm.getCount();
        }
        
        if(count > 0){
            publishbutton.setDisabled(false);
            unpublishbutton.setDisabled(false);
            deletebutton.setDisabled(false);
        }else{
            publishbutton.setDisabled(true);
            unpublishbutton.setDisabled(true);
            deletebutton.setDisabled(true);
        }
    }
    
    function getSelectedItems()
    {
        var arrayofids = new Array();
        rows = sm.getSelections();
        
        for(x = 0; x < rows.length; x++){
            arrayofids[x] = rows[x].data.id;
        }
        
        return arrayofids;
    }
    
    function deleteSelectedAnnouncements()
    {
        var confirmmsg = lang("Click OK if you are sure you want to delete the selected items.");
        var deleteItems = confirm(confirmmsg);
        
        if(deleteItems == false){
           return false;
        }
        
        Ext.Ajax.request({
            url:      "index.php?fuse=admin&action=adminDeleteAnnouncements",
            success:  function(xhr){
                //refreshgrid
                grid.enable();
                gridstore.load({
                    params: {
                        start:  0
                    }
                });
                toggleButtons(0, 0);
                
                var data = Ext.util.JSON.decode(xhr.responseText);
                
                if(data.error){
                    msg(lang("There was an error performing this action"));
                }else if(data.message){
                    msg(data.message);
                }
            },
            failure:  function(){
                grid.enable();
                Ext.Msg.alert("Fail");
            },
            params:   {
                items:  Ext.util.JSON.encode(getSelectedItems())
            }
        });
        
        return true;
    }
    
    function publishUnpublishSelectedAnnouncements(publish)
    {
        Ext.Ajax.request({
            url:      "index.php?fuse=admin&action=adminPublishUnpublishAnnouncements",
            success:  function(xhr){
                //refreshgrid
                grid.enable();
                gridstore.load({
                    params: {
                        start:  0
                    }
                });
                toggleButtons(0, 0);
                
                var data = Ext.util.JSON.decode(xhr.responseText);
                
                if(data.error){
                    msg(lang("There was an error performing this action"));
                }else if(data.message){
                    msg(data.message);
                }
            },
            failure:  function(){
                grid.enable();
                Ext.Msg.alert("Fail");
            },
            params:   {
                publish:  publish,
                items:    Ext.util.JSON.encode(getSelectedItems())
            }
        });
        
        return true;
    }
    
    var grid = new Ext.grid.GridPanel({
        el:               'announcments-grid',
        autoHeight:       true,
        store:            gridstore,
        trackMouseOver:   true,
        disableSelection: true,
        loadMask:         true,
        columns:          [
            sm,
            {
                id:         'id',
                header:     lang("Id"),
                width:      50,
                dataIndex:  "id",
                hidden:     true,
                sortable:   true,
                align:      "left"
            },
            {
                id:         'aTitle',
                header:     lang("Title"),
                width:      300,
                dataIndex:  "title",
                renderer:   renderTitle,
                sortable:   true,
                hidden:     false
            },
            {
                id:         'aPublished',
                header:     lang("Published"),
                dataIndex:  "published",
                renderer:   renderPublished,
                width:      50,
                hidden:     false,
                sortable:   true
            },
            {
                id:         'aPostDate',
                header:     lang("Post Date"),
                dataIndex:  "postdate",
                width:      50,
                hidden:     false,
                sortable:   true,
                align:      "center"
            }
        ],
        sm:               sm,
        stripeRows:       true,
        viewConfig:       {
            forceFit:       true,
            enableRowBody:  true,
            emptyText:      lang("There are currently no announcements to view"),
            scrollOffset:   1
        },
        bbar:             announcementgridbb,
        buttonAlign:      'left',
        buttons:          [
            publishbutton = new Ext.Button({
                id:         'publishbutton',
                autoHeight: true,
                xtype:      'button',
                text:       lang('Publish'),
                disabled:   true,
                handler:    function(){
                    publishUnpublishSelectedAnnouncements(1);
                }
            }),
            unpublishbutton = new Ext.Button({
                id:         'unpublishbutton',
                autoHeight: true,
                xtype:      'button',
                text:       lang('Unpublish'),
                disabled:   true,
                handler:    function(){
                    publishUnpublishSelectedAnnouncements(0);
                }
            }),
            deletebutton = new Ext.Button({
                id:         'deletebutton',
                autoHeight: true,
                xtype:      'button',
                text:       lang('Delete'),
                disabled:   true,
                handler:    function(){
                    deleteSelectedAnnouncements();
                }
            })
        ],
        listeners:        {
            'sortchange': function (grid,sortInfo){
                gridsavedstate.sortinfo.field = sortInfo.field;
                gridsavedstate.sortinfo.dir = sortInfo.direction;
                updateGridSavedState("AnnouncementGridState");
            }
        }
    });
    
grid.restoreState();


    function updateGridSavedState(customfield){
        Ext.Ajax.request({
           url: 'index.php?fuse=admin&action=updateGridSavedState',
           success: function(xhr) {
                    //msg('Settings Update Successfully','');
                    },
           failure: function() {
                NE_log(1,"Failed from saving gridstate");
           },
           params: { gridcustomfield: customfield,
                     gridsavedstate: Ext.encode(gridsavedstate),
                     columnsavedstate: Ext.util.JSON.encode(columnsavedstate)
                     },
           method:'post'
        });
    }
    
    // render it
    grid.render();
    gridstore.load({
        params: {
            start:  0
        }
    });
    
    // create the combo instance
    new Ext.form.ComboBox({
        triggerAction:  'all',
        lazyRender:     true,
        editable:       false,
        value:          gridsavedstate.displaysize,
        mode:           'local',
        store:          new Ext.data.ArrayStore({
            id:     0,
            fields: [
                'myId',
                'displayText'
            ],
            data:   [
                [10, '10'],
                [25, '25'],
                [50, '50']
            ]
        }),
        valueField:     'myId',
        width:          50,
        displayField:   'displayText',
        applyTo:        'numlistfilter',
        listeners:      {
            'select': function(cb,record){
                gridstore.setBaseParam('limit', record.data.myId);
                announcementgridbb.pageSize = record.data.myId;
                gridstore.load({
                    params: {
                        start:  0
                    }
                });
                gridsavedstate.displaysize = record.data.myId;
                updateGridSavedState("AnnouncementGridState");
            }
        }
    });
});
//end extjsopen

function createAnnouncementWin()
{
//  routingId
    announcementId = new Ext.form.Hidden({
        id:               'id',
        name:             'id',
        value:            '0',
        validationEvent:  false
    });

// Excerpt
     var excerptTip = lang('Any text included here will be added as a summary of your announcement.  If left blank the first couple hundred characters will be used as an excerpt.');
    announcementExcerpt = new Ext.form.TextArea({
        id:         'excerpt',
        name:       'excerpt',
        labelAlign: 'top',
        anchor:     '98%',
        fieldLabel:  "<span style='border-bottom: 1px solid rgb(223, 223, 223); top: 0px;' class='tip-target' qtip='" + excerptTip.replace(/'/g, "&#39;") + "'>" + lang("Excerpt") + "</span>",
        allowBlank: true
    });
    
// Post Date
    
    announcementPostDate = new Ext.form.DateField({
        id:         'postdate',
        name:       'postdate',
        labelAlign: 'top',
        fieldLabel: lang("Date"),
        format:     'm/d/Y',
        value:      duedatevalue,
        allowBlank: false
    });

// Post Time
announcementPostTime = new Ext.form.TimeField({
        id:         'posttime',
        name:       'posttime',
        labelAlign: 'top',
        fieldLabel: lang("Time"),
        format:     'h:i a',
        value:      posttimevalue,
        allowBlank: false
    });

// Title
    announcementTitle = new Ext.form.TextField({
        id:               'title',
        name:             'title',
        labelAlign:       'top',
        fieldLabel:       lang("Title"),
        validationEvent:  false,
        validateOnBlue: false,
        anchor:           '98%',
        border:           false,
        value:            '',
        allowBlank:       false
    });
    
// Content
    announcementPost = new Ext.form.HtmlEditor({
        id:         'post',
        name:       'post',
        value:      '',
        hideLabel:  true,
        anchor:     '98%',
        height:     200,
        x:          5,
        y:          40,
        hideMode:   'offsets',
        allowBlank: false
    });
    
    announcementPostValidate = function(){
        if(announcementPost != undefined){
            if(announcementPost.getValue() != ''){
                announcementPost.clearInvalid();
                return true;
            }else{
                announcementPost.markInvalid('This field is required');
                return false;
            }
        }else{
            return false;
        }
    }
    
// Publish
    announcementPublish = new Ext.form.Checkbox({
        id:         'published',
        name:       'published',
        labelAlign: 'right',
        hideLabel:  true,
        checked:    false,
        labelStyle: 'font-weight:bold;',
        boxLabel:   lang("Publish this announcement to the recipients")
    });
    
// E-mail
    announcementEmail = new Ext.form.Checkbox({
        id:         'email',
        name:       'email',
        labelAlign: 'right',
        hideLabel:  true,
        checked:    false,
        labelStyle: 'font-weight:bold;',
        boxLabel:   lang("E-mail this announcement to the recipients")
    });
    
    announcementEmail.on('check', hideShowOverrideOptOut);
    
    function hideShowOverrideOptOut(){
        if(announcementEmail != undefined
          && announcementEmail.getValue() == true){
            announcementOverrideOptOut.show();
        }else{
            announcementOverrideOptOut.hide();
            announcementOverrideOptOut.setValue(false);
        }
    }
    
// Override Opt-Out
    var helpOverrideOptOut = lang('Use this to force the emailing of this announcement to customers who have opted out of announcements.');
    
    announcementOverrideOptOut = new Ext.form.Checkbox({
        id:         'override',
        name:       'override',
        labelAlign: 'right',
        hideLabel:  true,
        checked:    false,
        hidden:     true,
        labelStyle: 'font-weight:bold;',
        boxLabel:   "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpOverrideOptOut.replace(/'/g, "&#39;") + "'>" + lang("Override Opt-Out") + "</span>"
    });
    
// Recipients
    announcementRecipients = new Ext.form.ComboBox({
        id:               'recipientType',
        name:             'recipientType',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Recipients"),
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'recipienttypename'
            ],
            data:     [
                [
                    0,
                    lang("Public Announcement")
                ],
                [
                    1,
                    lang("Select Client Statuses")
                ],
//                [
//                    2,
//                    lang("Select Clients")
//                ],
                [
                    3,
                    lang("Select Servers")
                ],
                [
                    4,
                    lang("Select Product Groups")
                ]
            ]
        }),
        valueField:       'id',
        displayField:     'recipienttypename',
        value:            0,
        hiddenId:         'recipientTypeValue',
        hiddenName:       'recipientTypeValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
    announcementRecipients.on('afterrender', hideShowRecipientsOptions);
    announcementRecipients.on('select', hideShowRecipientsOptions);
    
    function hideShowRecipientsOptions(){
        hideShowStatusTarget();
//        hideShowUserTarget();
        hideShowServerTarget();
        hideShowPackageTarget();
    }
    
// Status Target
    announcementStatusTarget = new Ext.ux.form.LovCombo({
        id:               'statustarget',
        name:             'statustarget',
        fieldLabel:       lang("Select client statuses"),
        validationEvent:  false,
        width:            defaultWidth,
        hideOnSelect:     true,
        maxHeight:        200,
        allowBlank:       false,
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'statusname'
            ],
            data:     [
                [
                    1,
                    lang("Active")
                ],
                [
                    -1,
                    lang("Inactive")
                ],
                [
                    -2,
                    lang("Cancelled")
                ],
                [
                    0,
                    lang("Pending")
                ],
                [
                    -3,
                    lang("Fraud")
                ]
            ]
        }),
        valueField:       'id',
        displayField:     'statusname',
        value:            '',
        hiddenId:         'statustargetValue',
        hiddenName:       'statustargetValue',
        
        separator:        ';',
        //The separator is used in both valueField and displayField
        //By default, it is a comma (,)
        //No matter what separator do you use, if it is present in the value or name of one
        //of its elements in the store, LovCombo will get confused when you select that element
        
        triggerAction:    'all',
        mode:             'local',
        beforeBlur:       Ext.emptyFn
    });
    
    announcementStatusTargetValidate = function(){
        if(announcementRecipients != undefined
          && announcementRecipients.getValue() == 1){
            if(announcementStatusTarget != undefined){
                if(announcementStatusTarget.getValue() != ''){
                    announcementStatusTarget.clearInvalid();
                    return true;
                }else{
                    announcementStatusTarget.markInvalid('This field is required');
                    return false;
                }
            }else{
                return false;
            }
        }else{
            if(announcementStatusTarget != undefined){
                announcementStatusTarget.clearInvalid();
            }
            
            return true;
        }
    }
    
    announcementStatusTargetContainer = new Ext.Container({
        id:       'announcementStatusTargetContainer',
        layout:   'form',
        items :   [
            announcementStatusTarget
        ],
        hideMode: 'offsets',
        hidden:   true
    });
    
    function hideShowStatusTarget(){
        if(announcementStatusTargetContainer != undefined){
            if(announcementRecipients.getValue() == 1){
                announcementStatusTargetContainer.show();
            }else{
                announcementStatusTargetContainer.hide();
                announcementStatusTarget.setValue('');
            }
        }
    }
    
// Server Target
    var serverstore = new Ext.data.JsonStore({
        id:             "serverstore",
        root:           'servers',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
        },
        fields:         [
            'serverid',
            'servername'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=admin&action=Admin_GetServers'
        })
    });
    
    serverstore.setDefaultSort('id', 'asc');
    
    serverstore.load();
    
    announcementServerTarget = new Ext.ux.form.LovCombo({
        id:               'servertarget',
        name:             'servertarget',
        fieldLabel:       lang("Select servers"),
        validationEvent:  false,
        width:            defaultWidth,
        hideOnSelect:     true,
        maxHeight:        200,
        allowBlank:       false,
        store:            serverstore,
        valueField:       'serverid',
        displayField:     'servername',
        value:            '',
        hiddenId:         'servertargetValue',
        hiddenName:       'servertargetValue',
        
        separator:        ';',
        //The separator is used in both valueField and displayField
        //By default, it is a comma (,)
        //No matter what separator do you use, if it is present in the value or name of one
        //of its elements in the store, LovCombo will get confused when you select that element
        
        triggerAction:    'all',
        mode:             'local',
        beforeBlur:       Ext.emptyFn
    });
    
    announcementServerTargetValidate = function(){
        if(announcementRecipients != undefined
          && announcementRecipients.getValue() == 3){
            if(announcementServerTarget != undefined){
                if(announcementServerTarget.getValue() != ''){
                    announcementServerTarget.clearInvalid();
                    return true;
                }else{
                    announcementServerTarget.markInvalid('This field is required');
                    return false;
                }
            }else{
                return false;
            }
        }else{
            if(announcementServerTarget != undefined){
                announcementServerTarget.clearInvalid();
            }
            
            return true;
        }
    }
    
    announcementServerTargetContainer = new Ext.Container({
        id:       'announcementServerTargetContainer',
        layout:   'form',
        items :   [
            announcementServerTarget
        ],
        hideMode: 'offsets',
        hidden:   true
    });
    
    function hideShowServerTarget(){
        if(announcementServerTargetContainer != undefined){
            if(announcementRecipients.getValue() == 3){
                announcementServerTargetContainer.show();
            }else{
                announcementServerTargetContainer.hide();
                announcementServerTarget.setValue('');
            }
        }
    }
    
// Package Target
    var productgroupstore = new Ext.data.JsonStore({
        id:             "productgroupstore",
        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.load();
    
    announcementPackageTarget = new Ext.ux.form.LovCombo({
        id:               'packagetarget',
        name:             'packagetarget',
        fieldLabel:       lang("Select product groups"),
        validationEvent:  false,
        width:            defaultWidth,
        hideOnSelect:     true,
        maxHeight:        200,
        allowBlank:       false,
        store:            productgroupstore,
        valueField:       'id',
        displayField:     'name',
        value:            '',
        hiddenId:         'packagetargetValue',
        hiddenName:       'packagetargetValue',
        
        separator:        ';',
        //The separator is used in both valueField and displayField
        //By default, it is a comma (,)
        //No matter what separator do you use, if it is present in the value or name of one
        //of its elements in the store, LovCombo will get confused when you select that element
        
        triggerAction:    'all',
        mode:             'local',
        beforeBlur:       Ext.emptyFn
    });
    
    announcementPackageTargetValidate = function(){
        if(announcementRecipients != undefined
          && announcementRecipients.getValue() == 4){
            if(announcementPackageTarget != undefined){
                if(announcementPackageTarget.getValue() != ''){
                    announcementPackageTarget.clearInvalid();
                    return true;
                }else{
                    announcementPackageTarget.markInvalid('This field is required');
                    return false;
                }
            }else{
                return false;
            }
        }else{
            if(announcementPackageTarget != undefined){
                announcementPackageTarget.clearInvalid();
            }
            
            return true;
        }
    }
    
    announcementPackageTargetContainer = new Ext.Container({
        id:       'announcementPackageTargetContainer',
        layout:   'form',
        items :   [
            announcementPackageTarget
        ],
        hideMode: 'offsets',
        hidden:   true
    });
    
    function hideShowPackageTarget(){
        if(announcementPackageTargetContainer != undefined){
            if(announcementRecipients.getValue() == 4){
                announcementPackageTargetContainer.show();
            }else{
                announcementPackageTargetContainer.hide();
                announcementPackageTarget.setValue('');
            }
        }
    }
    
// FORM
    simpleForm = new Ext.FormPanel({
        id:           'simpleForm',
        name:         'simpleForm',
        frame:        true,
        hideBorders:  true,
        labelAlign:   'top',
        shadow:       false,
        floating:     false,
        autoHeight:   true,
        title:        '',
        bodyStyle:    'padding:5px 5px 0',
        width:        650,
        items:        [
            announcementId,
            {
                layout: 'column',
                border: false,
                items:  [
                    {
                        columnWidth:  0.6,
                        layout:       'form',
                        border:       false,
                        items:        [
                            announcementTitle
                        ]
                    },
                    {
                        columnWidth:  0.2,
                        layout:       'form',
                        border:       false,
                        items:        [
                            announcementPostDate
                        ]
                    },
                    {
                        columnWidth:  0.2,
                        layout:       'form',
                        border:       false,
                        items:        [
                            announcementPostTime
                        ]
                    }
                ]
            },
            announcementExcerpt,
            announcementPost,
            {
                layout: 'column',
                border: false,
                items:  [
                    {
                        columnWidth:  0.5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            announcementRecipients
                        ]
                    },
                    {
                        columnWidth:  0.5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            announcementStatusTargetContainer,
//                            announcementUserTargetContainer,
                            announcementServerTargetContainer,
                            announcementPackageTargetContainer
                        ]
                    }
                ]
            },
            {
                layout: 'column',
                border: false,
                items:  [
                    {
                        columnWidth:  0.5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            announcementPublish
                        ]
                    },
                    {
                        columnWidth:  0.5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            announcementEmail,
                            announcementOverrideOptOut
                        ]
                    }
                ]
            }
        ]
    });
    
    simpleForm.on('actioncomplete', function(form,action){
        if(action.type == "load"){
            var res = Ext.util.JSON.decode(action.response.responseText);
            //if(res.data.published == "1"){
            //    Ext.getCmp('publishedcb').setValue(true);
            //}
            
            hideShowRecipientsOptions();
        }
    });
    
    announcementWin = new Ext.Window({
        id:         "announcementWindow",
        y:          100,
        layout:     'fit',
        width:      650,
        autoHeight: true,
        modal:      true,
        closable:   false,
        title:      lang("Announcement"),
        plain:      true,
        shadow:     false,
        items:      [
            simpleForm
        ],
        fbar:       [
            {
                text:     'Close',
                handler:  function(){
                    announcementWin.hide();
                    announcementWin.destroy();
                }
            },
            {
                id:       'btnSave',
                text:     lang("Save"),
                disabled: false,
                hidden:   false,
                handler:  function(){
                    if(announcementTitle.validate()
                      && announcementPostDate.validate()
                      && announcementPostTime.validate()
                      && announcementPostValidate()             //&& announcementPost.validate()
                      && announcementStatusTargetValidate()     //&& announcementStatusTarget.validate()
                      && announcementServerTargetValidate()     //&& announcementServerTarget.validate()
                      && announcementPackageTargetValidate()){  //&& announcementPackageTarget.validate()){
                        showAnnouncementWaitingMask();

                        Ext.Ajax.request({
                           url: 'index.php?fuse=admin&action=adminSaveAnnouncement',
                           success: function(t) {
                                onCompleteSaveAnnouncement(t);
                           },
                           params: {id:announcementId.getValue(),
                                    excerpt:announcementExcerpt.getValue(),
                                    postdate:announcementPostDate.getRawValue(),
                                    posttime:announcementPostTime.getRawValue(),
                                    title:announcementTitle.getValue(),
                                    post:announcementPost.getValue(),
                                    published:announcementPublish.getValue(),
                                    email:announcementEmail.getValue(),
                                    override:announcementOverrideOptOut.getValue(),
                                    recipientType:announcementRecipients.getValue(),
                                    statustarget:announcementStatusTarget.getValue(),
                                    servertarget:announcementServerTarget.getValue(),
                                    packagetarget:announcementPackageTarget.getValue()
                                  }
                        });


                    }else{
                        message = '';
                        newline = "<br>";
                        
                        if(!announcementTitle.validate()){
                            if(message != ''){
                                message += newline;
                            }
                            
                            message += lang("Title");
                        }
                        
                        if(!announcementPostDate.validate()){
                            if(message != ''){
                                message += newline;
                            }
                            
                            message += lang("Date");
                        }

                        if(!announcementPostTime.validate()){
                            if(message != ''){
                                message += newline;
                            }

                            message += lang("Time");
                        }
                        
                        if(!announcementPostValidate()){ //if(!announcementPost.validate()){
                            if(message != ''){
                                message += newline;
                            }
                            
                            message += lang("Content");
                        }
                        
                        if(!announcementStatusTargetValidate()){ //if(!announcementStatusTarget.validate()){
                            if(message != ''){
                                message += newline;
                            }
                            
                            message += lang("Select client statuses");
                        }
                        
//                        if(!announcementUserTargetValidate()){ //if(!announcementUserTarget.validate()){
//                            if(message != ''){
//                                message += newline;
//                            }
//                            
//                            message += lang("Select clients");
//                        }
                        
                        if(!announcementServerTargetValidate()){ //if(!announcementServerTarget.validate()){
                            if(message != ''){
                                message += newline;
                            }
                            
                            message += lang("Select servers");
                        }
                        
                        if(!announcementPackageTargetValidate()){ //if(!announcementPackageTarget.validate()){
                            if(message != ''){
                                message += newline;
                            }
                            
                            message += lang("Select product groups");
                        }
                        
                        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;
                        }
                    }
                }
            }
        ]
    });
    
    function onCompleteSaveAnnouncement(responseObj){
        hideAnnouncementWaitingMask();
        
        var data = Ext.util.JSON.decode(responseObj.responseText);
        
        if(data.error){
            if(data.message){
                Ext.MessageBox.alert(lang("Errors"), data.message);
            }else{
                Ext.MessageBox.alert(lang("Errors"), "There was an error performing this action");
            }
            
            return;
        }else if(data.message){
            msg(data.message);
        }else{
            msg(lang("Action have been performed"));
        }
        
        announcementWin.hide();
        announcementWin.destroy();
        
        gridstore.load({
            params: {
                start:  0
            }
        });
    }
    
    function showAnnouncementWaitingMask(){
        announcementWaitingMask = new Ext.LoadMask('announcementWindow', {msg:"Please wait..."});
        
        announcementWaitingMask.show();
    }
    
    function hideAnnouncementWaitingMask(){
        announcementWaitingMask.hide();
    }
    
    announcementWin.show();
    announcementTitle.focus('',300);
    announcementTitle.clearInvalid();
}

function emailCustomer(id)
{
    createAnnouncementWin();
    
    if(id != null){
        simpleForm.getForm().load({
            url:      'index.php?fuse=admin&action=adminGetAnnouncement&id=' + id,
            waitMsg:  lang('Loading')
        });
    }
}