var OutgoingQueueFrame = {
	Name: "OutgoingQueueFrame",
  SelectedListRows: new Array(),
	Query: {NewQuery: false, QueryString: "", QueryType: 1, QueueType: 1, Page: 0, Rows: 1, SortField: "", SortDirection: ""},
 
  InitFrame: function() {
 	  OutgoingQueueFrame.CreateOutgoingQueueList();	
    jQuery("#OutgoingQueueListPanel").contextMenu({menu: 'OutgoingQueueListMenu'}, OutgoingQueueFrame.HandleListMenu);
		jQuery("#OutgoingQueueListPanel").disableContextMenuItems(null);
    jQuery("#OutgoingQueueQueryForm").submit(OutgoingQueueFrame.SubmitOutgoingQueueQuery);
	},

  ShowFrame: function() {
		jQuery('#OutgoingQueueFrame').show();
    OutgoingQueueFrame.OnFrameResize();
		
		// Load list if empty
		var count = jQuery("#OutgoingQueueList").getGridParam('reccount');
		if ((count == null) || (count == 0)) {
		  OutgoingQueueFrame.SubmitOutgoingQueueQuery();
		}	
		
		SetWindowKeyPressHandler(OutgoingQueueFrame.OnKeyPress);
  },

  HideFrame: function() {
    jQuery('#OutgoingQueueFrame').hide();
  },

	OnKeyPress: function(event) {
		switch (event.keyCode) {
			case 116:
				OutgoingQueueFrame.SubmitOutgoingQueueQuery();
				return false;
				break;
		}
	},
	
	OnLogoff: function() {
		jQuery("#OutgoingQueueList").clearGridData();	  
	},
	
  OnFrameResize: function() {
		var listWidth = jQuery("#OutgoingQueueInputPanel").width();
		var listHeight = Layout.state.container.innerHeight - Layout.state.north.size - Layout.state.south.size;
		listHeight = listHeight - jQuery("#OutgoingQueueInputPanel").height() - jQuery('#OutgoingQueueListPager').height() - 40;
		
    jQuery("#OutgoingQueueList").setGridWidth(listWidth, false); 
    jQuery("#OutgoingQueueList").setGridHeight(listHeight); 
	},

  CreateOutgoingQueueList: function() {
    jQuery("#OutgoingQueueList").jqGrid({
			datatype: OutgoingQueueFrame.GetGridData,
			height: 250,
			colNames:['', '', _('Message ID'), _('Subject'), _('Sender'), _('Recipients'), _('Date'), _('Size'), _('Delivery time'), _('Last result')],
			colModel:[
				{name:'recipientID',index:'recipientID', width:20, hidden:true},
				{name:'image',index:'image', width:20, formatter:OutgoingQueueFrame.ImageFormatter},
				{name:'messageID',index:'messageID', width:100},
				{name:'subject',index:'subject', width:400},
				{name:'sender',index:'sender', width:300},
				{name:'recipients',index:'recipients', width:300},
				{name:'date',index:'date', width:200, sorttype:"date", formatter:"date", formatoptions:{srcformat:"Y-m-d\TH:i:s", newformat:"Y-m-d H:i:s"}},
				{name:'size',index:'size', width:100, sorttype:"integer", formatter:byteFormater},
				{name:'lastTry',index:'lastTry', width:200, sorttype:"date", formatoptions:{srcformat:"Y-m-d\TH:i:s", newformat:"Y-m-d H:i:s"}},
				{name:'lastResult',index:'lastResult', width:300}
				],
			imgpath: gridimgpath,
			pager: jQuery('#OutgoingQueueListPager'),
			autoencode: true,
			viewrecords: true,
			multiselect: true,
			rowNum:30, 
			sortname: 'date',
			sortorder: 'desc',
			onSelectRow: OutgoingQueueFrame.OnSelectRow,
			onSelectAll: OutgoingQueueFrame.OnSelectAll,
			onRightClickRow: OutgoingQueueFrame.OnRightClickRow,
			ondblClickRow: OutgoingQueueFrame.OnDblClickRow
    }); 
  },
	
	ImageFormatter: function (cellvalue, options, rowObject) {
    return '<img src="/gui/images/icons/outbox_out.png">';
	},

	BeginLoading: function() {
	  jQuery("#lui_OutgoingQueueList, #load_OutgoingQueueList").show();
	},

	EndLoading: function() {
		jQuery("#lui_OutgoingQueueList, #load_OutgoingQueueList").hide();
	},
	
	GetGridData: function(pdata) {
		if (jQuery('#OutgoingQueueFrame').is(':hidden')) {
			return;
		}
		
		OutgoingQueueFrame.BeginLoading();
		
		OutgoingQueueFrame.Query.Page = pdata.page;
		OutgoingQueueFrame.Query.Rows = pdata.rows;
	  OutgoingQueueFrame.Query.SortField = pdata.sidx;
		OutgoingQueueFrame.Query.SortDirection = pdata.sord;

    var service = new Spamfinder(serviceURL, Session.SessionID);

    service.QueryOutgoingQueue(OutgoingQueueFrame.Query,
      {
        success: OutgoingQueueFrame.QueryOutgoingQueue,
				failure: function(error) {
					OutgoingQueueFrame.EndLoading();
					ErrorHandler(error);
				}
      }
    );
	},
	
  HandleListMenu: function(action, el, pos) {
		switch(action) {
			case 'Preview':
	  	  if (OutgoingQueueFrame.SelectedListRows.length == 1) {
          var ID = jQuery("#OutgoingQueueList").getCell(OutgoingQueueFrame.SelectedListRows[0], 'messageID');
          OutgoingQueueFrame.OpenMessage(ID);
				}	
			  break;
		}
	},

  SubmitOutgoingQueueQuery: function() {
	  if (jQuery('#lui_OutgoingQueueList').is(':visible')) {
			jAlert(_("A query is already in progress. Please wait..."), _("Information"));
			return false;
		}
	
		OutgoingQueueFrame.Query.NewQuery = true;
		OutgoingQueueFrame.Query.QueryString = document.OutgoingQueueQueryForm.OutgoingQueueQuery.value;
		OutgoingQueueFrame.Query.QueryType = document.OutgoingQueueQueryForm.OutgoingQueryType.selectedIndex + 1;
		OutgoingQueueFrame.Query.QueueType = document.OutgoingQueueQueryForm.OutgoingQueueType.selectedIndex + 1;

    jQuery("#OutgoingQueueList").setGridParam({page:1}).trigger("reloadGrid");
		return false;
  },

  QueryOutgoingQueue: function(result) {
		var GridData = { total: 0,
		                 page: 0,
										 records: 0,
										 rows: new Array()
									 };
		
		OutgoingQueueFrame.Query.NewQuery = false;
		
		GridData.total = result.QueryResult.TotalPages;
		GridData.page = result.QueryResult.Page;
		GridData.records = result.QueryResult.Records;
		
	  jQuery("#OutgoingQueueList").clearGridData();
	  for (i = 0; i < result.QueryResult.Rows.length; i++) {
      var row = {id: 0,
			       cell: new Array()
			      };

      row.id = i;
			row.cell[0] = result.QueryResult.Rows[i].RecipientID;
			row.cell[1] = ''
			row.cell[2] = result.QueryResult.Rows[i].MessageID;       
			row.cell[3] = result.QueryResult.Rows[i].Subject;
			row.cell[4] = result.QueryResult.Rows[i].Sender;
			row.cell[5] = result.QueryResult.Rows[i].Recipient;
      row.cell[6] = result.QueryResult.Rows[i].Date;
			row.cell[7] = result.QueryResult.Rows[i].Size;
			row.cell[8] = result.QueryResult.Rows[i].LastTry;
			row.cell[9] = result.QueryResult.Rows[i].LastResult;

      GridData.rows[i] = row;
	  }

    JsonGridData = YAHOO.util.Lang.JSON.stringify(GridData);
		var thegrid = jQuery("#OutgoingQueueList")[0]; 
    thegrid.addJSONData(eval("("+JsonGridData+")")); 
		
		OutgoingQueueFrame.EndLoading();
  },

	UpdateMenuItems: function() {
	  jQuery("#OutgoingQueueListMenu").disableContextMenuItems(null);
	  if (OutgoingQueueFrame.SelectedListRows.length == 1) {
		  jQuery("#OutgoingQueueListMenu").enableContextMenuItems('#Preview');
		}
	},
	
	OnSelectAll: function(aRowids, status) {
	  OutgoingQueueFrame.SelectedListRows = jQuery("#OutgoingQueueList").getGridParam('selarrrow');
		OutgoingQueueFrame.UpdateMenuItems();
	},
	
  OnSelectRow: function(rowid, status) {
	  OutgoingQueueFrame.SelectedListRows = jQuery("#OutgoingQueueList").getGridParam('selarrrow');
		OutgoingQueueFrame.UpdateMenuItems();
	},

  OnRightClickRow: function(rowid, iRow, iCol) {
	  if (OutgoingQueueFrame.SelectedListRows.length == 0) {
		  jQuery("#OutgoingQueueList").setSelection(rowid, true);
		}	
  },

  OnDblClickRow: function(rowid, iRow, iCol) {
    var ID = jQuery("#OutgoingQueueList").getCell(rowid, 'messageID');
    OutgoingQueueFrame.OpenMessage(ID);	
  },

  OpenMessage: function(ID) {
		MailViewer.OpenMsg(MSGSRC_OUTGOING, ID, false, Session.GroupPolicy.SpamfinderRules.DisableAttachmentsInPreview);
	}
}
