/*
 * Copyright 2005 - 2009  Zarafa B.V.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3, 
 * as published by the Free Software Foundation with the following additional 
 * term according to sec. 7:
 *  
 * According to sec. 7 of the GNU Affero General Public License, version
 * 3, the terms of the AGPL are supplemented with the following terms:
 * 
 * "Zarafa" is a registered trademark of Zarafa B.V. The licensing of
 * the Program under the AGPL does not imply a trademark license.
 * Therefore any rights, title and interest in our trademarks remain
 * entirely with us.
 * 
 * However, if you propagate an unmodified version of the Program you are
 * allowed to use the term "Zarafa" to indicate that you distribute the
 * Program. Furthermore you may use our trademarks where it is necessary
 * to indicate the intended purpose of a product or service provided you
 * use it in accordance with honest practices in industrial or commercial
 * matters.  If you want to propagate modified versions of the Program
 * under the name "Zarafa" or "Zarafa Server", you may only do so if you
 * have a written permission by Zarafa B.V. (to acquire a permission
 * please contact Zarafa at trademark@zarafa.com).
 * 
 * The interactive user interface of the software displays an attribution
 * notice containing the term "Zarafa" and/or the logo of Zarafa.
 * Interactive user interfaces of unmodified and modified versions must
 * display Appropriate Legal Notices according to sec. 5 of the GNU
 * Affero General Public License, version 3, when you propagate
 * unmodified or modified versions of the Program. In accordance with
 * sec. 7 b) of the GNU Affero General Public License, version 3, these
 * Appropriate Legal Notices must retain the logo of Zarafa or display
 * the words "Initial Development by Zarafa" if the display of the logo
 * is not reasonably feasible for technical reasons."
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *  
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

maillistmodule.prototype = new ListModule;
maillistmodule.prototype.constructor = maillistmodule;
maillistmodule.superclass = ListModule.prototype;

function maillistmodule(id, element, title, data)
{
	if(arguments.length > 0) {
		this.init(id, element, title, data);
	}
}

maillistmodule.prototype.init = function(id, element, title, data)
{
	maillistmodule.superclass.init.call(this, id, element, title, data);

	this.menuItems.push(webclient.menu.createMenuItem("seperator", ""));
	this.menuItems.push(webclient.menu.createMenuItem("reply", _("Reply"), _("Reply"), eventMailListReplyMessage));
	this.menuItems.push(webclient.menu.createMenuItem("replyall", _("Reply All"), _("Reply All"), eventMailListReplyAll));
	this.menuItems.push(webclient.menu.createMenuItem("forward", _("Forward"), _("Forward"), eventMailListForwardMessage));
	this.menuItems.push(webclient.menu.createMenuItem("seperator", ""));
	this.menuItems.push(webclient.menu.createMenuItem("search", _("Search"), _("Quick Search"), eventMailListSearchBar, "S", true));
	this.menuItems.push(webclient.menu.createMenuItem("seperator", ""));
	this.menuItems.push(webclient.menu.createMenuItem("rules", _("Rules"), _("Edit e-mail rules"), eventMailListRules));
	this.menuItems.push(webclient.menu.createMenuItem("seperator", ""));
	//Add one more button to the main menu bar for performing the action of restore items
	this.menuItems.push(webclient.menu.createMenuItem("restoreitem", _("Restore Items"), _("Restore deleted Items") , eventRestoreItems));

	this.menuItems.push(webclient.menu.createMenuItem("seperator", ""));
	this.menuItems.push(webclient.menu.createMenuItem("send_receive", _("Send/Receive"), _("Send or Receive mails") , eventSendReceiveItems));

	webclient.menu.buildTopMenu(this.id, "createmail", this.menuItems, eventListNewMessage);
	
	var items = new Array();
	items.push(webclient.menu.createMenuItem("open", _("Open"), false, eventListContextMenuOpenMessage));
	items.push(webclient.menu.createMenuItem("print", _("Print"), false, eventListContextMenuPrintMessage));
	items.push(webclient.menu.createMenuItem("seperator", ""));
	items.push(webclient.menu.createMenuItem("reply", _("Reply"), false, eventMailListContextMenuReply));
	items.push(webclient.menu.createMenuItem("replyall", _("Reply All"), false, eventMailListContextMenuReplyAll));
	items.push(webclient.menu.createMenuItem("forward", _("Forward"), false, eventMailListContextMenuForward));
	items.push(webclient.menu.createMenuItem("seperator", ""));
	items.push(webclient.menu.createMenuItem("markread", _("Mark Read"), false, eventMailListContextMenuMessageFlag));
	items.push(webclient.menu.createMenuItem("markunread", _("Mark Unread"), false, eventMailListContextMenuMessageFlag));
	items.push(webclient.menu.createMenuItem("categories", _("Categories")+"...", false, eventListContextMenuCategoriesMessage));
	items.push(webclient.menu.createMenuItem("seperator", ""));
	items.push(webclient.menu.createMenuItem("flag_status_red", _("Red Flag"), false, eventMailListContextMenuRedFlag));
	items.push(webclient.menu.createMenuItem("flag_status_complete", _("Flag Complete"), false, eventMailListContextMenuFlagComplete));
	items.push(webclient.menu.createMenuItem("flagno", _("Delete Flag"), false, eventMailListContextMenuDeleteFlag));
	items.push(webclient.menu.createMenuItem("seperator", ""));
	items.push(webclient.menu.createMenuItem("junk", _("Move to Junk Folder"), false, eventListContextMenuMoveJunkMessage));
	items.push(webclient.menu.createMenuItem("delete", _("Delete"), false, eventListContextMenuDeleteMessage));
	//items.push(webclient.menu.createMenuItem("copy", _("Copy/Move Message"), false, eventListContextMenuCopyMessage));
	items.push(webclient.menu.createMenuItem("seperator", ""));
	items.push(webclient.menu.createMenuItem("options", _("Options")+"...", false, eventListContextMenuMessageOptions));

	webclient.pluginManager.triggerHook('client.module.maillistmodule.contextmenu.buildup', {contextmenu: items});
	this.contextmenu = items;
	
	this.layoutmenu = new Array();
	
	var previewMode = webclient.settings.get("global/previewpane","right"); // global default
	previewMode = webclient.settings.get("folders/entryid_"+this.entryid+"/previewpane",previewMode);
	this.layoutmenu.push(webclient.menu.createMenuItem("previewpane_right", _("Previewpane right"), false, eventLayoutSwitchPreviewpane));
	this.layoutmenu.push(webclient.menu.createMenuItem("previewpane_bottom", _("Previewpane bottom"), false, eventLayoutSwitchPreviewpane));
	this.layoutmenu.push(webclient.menu.createMenuItem("previewpane_off", _("Previewpane off"), false, eventLayoutSwitchPreviewpane));

	// Handle events from listmodule
	this.addEventHandler("selectitem", this, this.onSelectItem);
	this.addEventHandler("deletitem", this, this.onDeleteItem);

	this.initializeView();
}

maillistmodule.prototype.execute = function(type, action)
{
	webclient.pluginManager.triggerHook('client.module.maillistmodule.execute.before', {type: type, action: action});
	webclient.menu.showMenu();
		
	switch(type)
	{
		case "list":
			this.messageList(action);
			break;
		case "item":
			this.item(action);
			break;
		case "delete":
			this.deleteItems(action);
			break;
		case "swap":
			this.swapItems(action);
			break;
		case "search":
			this.updateSearch(action);
			break;
		case "failed":
			this.handleActionFailure(action);
			break;
	}
}

maillistmodule.prototype.messageList = function(action)
{
    var title = dhtml.getXMLValue(action, "folder_title");
	var entryid = dhtml.getXMLValue(action, "entryid");
    var storeid = dhtml.getXMLValue(action, "storeid");
    var isinbox = dhtml.getXMLValue(action, "isinbox");

	if(title) {
		// if title is already added, then change only folder name
		titleBar = dhtml.getElementsByClassNameInElement(dhtml.getElementById("main"), "zarafa_title")[0];
		if(titleBar) {
			titleBar.firstChild.firstChild.nodeValue = title;
		} else {
			this.setTitle(title, false, true);
		}
    }

    if(storeid && entryid) {
        this.entryid = entryid;
        this.storeid = storeid;
        if(this.previewreadmailitemmodule)
            this.previewreadmailitemmodule.setData(this.storeid, this.entryid);
    }
    this.isinbox = isinbox;

    maillistmodule.superclass.messageList.call(this, action);
}


function eventLayoutSwitchPreviewpane(moduleObject, element, event){
	element.parentNode.style.display = "none";
	var previewMode;
	if (dhtml.hasClassName(element, "icon_previewpane_off")){
		previewMode = "off";
	}else if (dhtml.hasClassName(element, "icon_previewpane_right")){
		previewMode = "right";
	}else if (dhtml.hasClassName(element, "icon_previewpane_bottom")){
		previewMode = "bottom";
	}
	
	webclient.settings.set("folders/entryid_"+this.entryid+"/previewpane",previewMode);
	if(this.isinbox)
	    webclient.settings.set("folders/entryid_inbox/previewpane",previewMode);

	webclient.hierarchy.selectLastFolder(true); // reload this folder
}

maillistmodule.prototype.initializeView = function()
{
	if (this.title!=false){
		this.setTitle(this.title, false, true);
	}
	this.topElement = dhtml.addElement(this.element, "div", "listview_topbar", "listview_topbar_"+this.id);

	this.contentElement = dhtml.addElement(this.element, "div");

	this.viewController.initView(this.id, "email", this.contentElement, this.events);
	
	// If the entryid is not set, then we're viewing the inbox
	var previewMode = webclient.settings.get("global/previewpane","right"); // global default
	if(!this.entryid)
    	previewMode = webclient.settings.get("folders/entryid_inbox/previewpane",previewMode);
    else
    	previewMode = webclient.settings.get("folders/entryid_"+this.entryid+"/previewpane",previewMode);
	
	if (previewMode == "right" || previewMode == "bottom"){
		this.previewreadmailitemmodule = webclient.dispatcher.loadModule("previewreadmailitemmodule");
		if(this.previewreadmailitemmodule) {
			var moduleID = webclient.addModule(this.previewreadmailitemmodule);
			this.previewPane = webclient.layoutmanager.addModule(moduleID, previewMode == "bottom" ? "main" : "right", BOX_LAYOUT, INSERT_ELEMENT_AT_BOTTOM);
			this.previewreadmailitemmodule.init(moduleID, this.previewPane);
			this.previewreadmailitemmodule.setData(this.storeid, this.entryid);
			if (previewMode == "right") {
				webclient.layoutmanager.updateElements("right");
				// Search bar is higher in smaller list view
				this.topElement.style.height = "45px";
			}
		}
	}else{
		this.previewPane = false;
	}

	this.initSearchBar();
}
/**
 * Function which sends a request to the server, with the action "list".
 * @param boolean useTimeOut use a time out for the request 
 */ 
maillistmodule.prototype.search = function(useTimeOut)
{
	if(this.storeid && this.entryid) {
		var data = new Object();
		data["store"] = this.storeid;
		data["entryid"] = this.entryid;

		this.sort = this.loadSortSettings();
		if(this.sort) {
			data["sort"] = new Object();
			data["sort"]["column"] = this.sort;
		}
		
		this.columns = this.loadFieldSettings();
		
		if(this.columns) {
			var tablecolumns = new Array();
			for(var i = 0; i < this.columns.length; i++)
			{
				var column = new Object();
				column["attributes"] = new Object();
				column["attributes"]["action"] = this.columns[i]["action"];
				
				if(this.columns[i]["order"]) {
					column["attributes"]["order"] = this.columns[i]["order"];
				}
				
				column["_content"] = this.columns[i]["id"];
				tablecolumns.push(column);	
			}
			
			data["columns"] = new Object();
			data["columns"]["column"] = tablecolumns;
			
			this.columns = new Array();
		}
		
		
		data["restriction"] = new Object();
		
		if(this.getRestrictionData) {
			data["restriction"] = this.getRestrictionData(); 
			if(data["restriction"] == false)
				return; // Abort list if module requires restriction but has none
		}
		
		data["restriction"]["start"] = this.rowstart;

		data["subfolders"] = this.searchSubfolders;

		// Retrieve data in extended (address cards view, calendar view, etc...) way 
		// or the normal (table) way.
		data["data_retrieval"] = (this.viewController.view=="table"?"normal":"extended");

		// Only show searchindicator when using a search folder
		if(this.storeid == webclient.hierarchy.defaultstore["id"]){
			this.enableSearchIndicator();
			this.isSearching = true;
		}

		webclient.xmlrequest.addData(this, "search", data);

		this.viewController.loadMessage();
	}
}

maillistmodule.prototype.enableSearchIndicator = function()
{
	var searchButton = dhtml.getElementById("searchfilterbutton");
	searchButton.className = "searchindicator";
}

maillistmodule.prototype.disableSearchIndicator = function()
{
	var searchButton = dhtml.getElementById("searchfilterbutton");
	searchButton.className = "searchfilterbutton";
}

maillistmodule.prototype.loadFieldSettings = function()
{
	if(webclient.hasRightPane){
		var path = "folders/entryid_"+this.entryid+"/fields";
		data = webclient.settings.get(path);
		var result = new Array();
		for(var i in data){
			switch(data[i]['id']){
				case ("display_to"):
				case ("sent_representing_name"):
				case ("client_submit_time"):
				case ("message_delivery_time"):
					result.push(data[i]);
					break;
			}
		}
		return result;
	}else {
		 return maillistmodule.superclass.loadFieldSettings.call(this);
	}
}

maillistmodule.prototype.updateSearch = function(action)
{
	var searchfolderentryid = dhtml.getXMLValue(action, "searchfolderentryid", false);
	var searchstate = dhtml.getXMLValue(action, "searchstate", 0);

	if (this.isSearching || this.finalSearchRequest){
		this.paging(action); // update paging
		this.finalSearchRequest = false;
	}

	if (this.isSearching){
		if ((searchstate & SEARCH_REBUILD) == SEARCH_REBUILD){
		    var module = this;
		    setTimeout(function() {
    			module.getSearchUpdate(searchfolderentryid);
            }, 1000);
		}else{
			// request for the last time an update, because it could happen the search is stopped
			// at the same time this request was made.
			this.getSearchUpdate(searchfolderentryid);
			this.isSearching = false;
			// This check is used to fetch the last paging result comes back from
			// the server when the this.isSearching is already set to false.
			this.finalSearchRequest = true;
		}
		this.enableSearchIndicator();
	}else{
		this.disableSearchIndicator();
	}
}

maillistmodule.prototype.getSearchUpdate = function(searchfolderentryid)
{
	var data = new Object();
	data["store"] = this.storeid;
	data["entryid"] = searchfolderentryid;

	webclient.xmlrequest.addData(this, "updatesearch", data);
	webclient.xmlrequest.sendRequest(); // we have to do this since we're not called from an event handler
}

maillistmodule.prototype.stopSearch = function()
{
	this.isSearching = false;
	this.disableSearchIndicator();

	var data = new Object();
	data["store"] = this.storeid;
	data["entryid"] = this.searchfolderentryid;

	webclient.xmlrequest.addData(this, "stopsearch", data);
}

maillistmodule.prototype.getRestrictionData = function()
{
	var result = new Object();
	if (this.filterRestriction){
		result["search"] = new Array();
		var targets = this.filterRestrictionTarget.split(" ");
		for (var i=0;i<targets.length;i++){
			var target = new Object();
			target["property"] = targets[i];
			target["value"] = this.filterRestriction;
			result["search"].push(target);
		}
	}
	return result;
}

maillistmodule.prototype.resize = function(action, messageEntryid)
{
	var elementHeight = (this.element.offsetHeight - this.contentElement.offsetTop) - 1;

	if (elementHeight<0) 
		elementHeight = 0;

	this.contentElement.style.height = (elementHeight) + "px";
	
	this.viewController.resizeView();
}

maillistmodule.prototype.replyMail = function(action, messageEntryid)
{
	this.setReadFlag(messageEntryid, "read,"+(this.sendReadReceipt(messageEntryid)?"receipt":"noreceipt"));

	webclient.openWindow(this, "createmail", DIALOG_URL+"task=createmail_standard&message_action=" + action + "&storeid=" + this.storeid + "&parententryid=" + this.entryid + "&entryid=" + messageEntryid);
}

maillistmodule.prototype.destructor = function()
{
	dhtml.removeEvent(document.body, "click", eventListCheckSelectedContextMessage);
	
	this.element.innerHTML = "";
	
	if(this.previewreadmailitemmodule) {
		this.previewreadmailitemmodule.destructor();
		webclient.deleteModule(this.previewreadmailitemmodule);
	}
	
	maillistmodule.superclass.destructor(this);
}

maillistmodule.prototype.initSearchBar = function()
{
	// create search bar
	var searchText = dhtml.addElement(this.topElement, "span", false, false, _("Search")+" "+NBSP);

	// create search target selector
	var filterTarget = dhtml.addElement(this.topElement, "select", "searchfiltertarget");
	(dhtml.addElement(filterTarget, "option", false, false,_("All text fields"))).value = "subject body sender_name sender_email sent_representing_name sent_representing_email to cc";
	(dhtml.addElement(filterTarget, "option", false, false,_("Subject"))).value = "subject";
	(dhtml.addElement(filterTarget, "option", false, false,_("Sender"))).value = "sender_name sender_email sent_representing_name sent_representing_email";
	(dhtml.addElement(filterTarget, "option", false, false,_("Body"))).value = "body";
	(dhtml.addElement(filterTarget, "option", false, false,_("Subject or Sender"))).value = "subject sender_name sender_email sent_representing_name sent_representing_email";
	(dhtml.addElement(filterTarget, "option", false, false,_("To or cc"))).value = "to cc";

	var defaultTarget = webclient.settings.get("folders/entryid_"+this.entryid+"/searchbar/target", "0");
	filterTarget.selectedIndex = defaultTarget;

	this.topElement.filterTarget = filterTarget; // add reference tot DOM

	dhtml.addTextNode(this.topElement, NBSP+" "+_("for")+" "+NBSP);

	var previewMode = webclient.settings.get("global/previewpane","right"); // global default
	previewMode = webclient.settings.get("folders/entryid_"+this.entryid+"/previewpane",previewMode);
	
	if (previewMode == "right"){
		// Create a two-line search bar
		dhtml.addElement(this.topElement, "br");

		// Shift inputbox to be directly under filterTarget
		var spacer = dhtml.addElement(this.topElement, "div", false, false, NBSP);
		spacer.style.marginLeft = (searchText.offsetWidth-3) + "px";
		spacer.style.display = "inline";
	}
	
	// create search input element
	var filterInputbox = dhtml.addElement(null, "input", "searchfilter");
	filterInputbox.setAttribute("type", "text");
	filterInputbox.setAttribute("autocomplete","off"); // workaround for Firefox 1.5 bug with autocomplete and emtpy string: "'Permission denied to get property XULElement.selectedIndex' when calling method: [nsIAutoCompletePopup::selectedIndex]"
	filterInputbox.value = "";

	dhtml.addEvent(this, filterInputbox, "click", eventMailListSearchBarFilterClick);
	dhtml.addEvent(this, filterInputbox, "mousedown", eventMailListSearchBarFilterClick);
	dhtml.addEvent(this, filterInputbox, "mousemove", eventMailListSearchBarFilterMouseMove);
	dhtml.addEvent(this, filterInputbox, "focus", eventMailListSearchBarFilterFocus);
	dhtml.addEvent(this, filterInputbox, "blur", eventMailListSearchBarFilterFocus);
	dhtml.addEvent(this, filterInputbox, "keydown", eventMailListSearchBarFilterKey);
	dhtml.addEvent(this, filterInputbox, "selectstart", eventMailListSearchBarFilterMouseMove);

	this.topElement.appendChild(filterInputbox);

	this.topElement.filterInputbox = filterInputbox; // add reference to DOM

	// subfolder search
	// Only show subfolders option in own store
	if(this.storeid == webclient.hierarchy.defaultstore["id"]){
		var searchSubfolders = dhtml.addElement(null, "input", "searchsubfolders", "searchsubfolders_"+this.id);
		searchSubfolders.setAttribute("type", "checkbox");
		this.topElement.appendChild(searchSubfolders);
		dhtml.addElement(this.topElement, "label", false, false, _("Subfolders")+NBSP).setAttribute("for","searchsubfolders_"+this.id);
		this.topElement.searchSubfolders = searchSubfolders;
	}

	// create buttons
	var filterButton = dhtml.addElement(this.topElement, "button", "searchfilterbutton", "searchfilterbutton", NBSP);
	dhtml.addEvent(this, filterButton, "click", eventMailListSearchBarSearch);

	var clearButton = dhtml.addElement(this.topElement, "button", "searchclearbutton", false, NBSP);
	dhtml.addEvent(this, clearButton, "click", eventMailListSearchBarClear);
	this.topElement.clearButton = clearButton; // add reference to DOM
	this.topElement.clearButton.disabled = true;

	// set the visibility of the search bar
	var displaySearch = webclient.settings.get("folders/entryid_"+this.entryid+"/searchbar/show","false");

	var searchMenuItem = dhtml.getElementById("search","a",this.menuBarLeft);
	if (displaySearch=="true"){
		this.topElement.style.display = "block";
		webclient.menu.toggleItem(searchMenuItem, true);
		this.resize();
	}else{
		this.topElement.style.display = "none";
		webclient.menu.toggleItem(searchMenuItem, false);
	}
}


maillistmodule.prototype.onDeleteItem = function(entryid)
{
	// Remove message in previewpane when selected message is deleted/moved
	if(this.previewPane && this.previewreadmailitemmodule && 
		this.previewreadmailitemmodule.itemEntryID == entryid) 
	{
		this.previewreadmailitemmodule.destructor();
	}
}

maillistmodule.prototype.onSelectItem = function(entryid)
{
	if(this.previewreadmailitemmodule) {
		if(this.previewreadmailitemmodule.messageentryid != entryid) {
			if (this.previewTimer){
				window.clearTimeout(this.previewTimer);
			}
			this.previewTimer = window.setTimeout("eventListPreviewTimer("+this.id+",'"+entryid+"')", 250);
		}
	}
}

/**
 * The previewpane needs to be updated when we sent a readreceipt (even if the 
 * user refuses to send one). The previewreadmailitemmodule is not updated like 
 * a listmodule, so it will not receive the updated message flags indicating the
 * read receipt has been sent. That is why we manually notify the previewpane of
 * this fact after we have handled the sending of the readreceipt.
 *
 * @param element HTMLElement TableRow of the selected message
 */
maillistmodule.prototype.sendReadReceipt = function(entryID)
{
	if(this.previewreadmailitemmodule) {
		this.previewreadmailitemmodule.readReceiptSent = true;
	}
	return maillistmodule.superclass.sendReadReceipt.call(this, entryID);
}

function eventListPreviewTimer(moduleID, entryid)
{
	moduleObject = webclient.getModule(moduleID);

	window.clearTimeout(moduleObject.previewTimer);
	moduleObject.previewTimer = null;

	if(moduleObject.previewreadmailitemmodule) {
		if(moduleObject.previewreadmailitemmodule.messageentryid != entryid) {
			moduleObject.previewreadmailitemmodule.open(entryid, entryid);
			moduleObject.previewreadmailitemmodule.loadMessage();
		}
	}
}

function eventMailListReplyMessage(moduleObject, element, event)
{
	if(moduleObject.selectedMessages.length > 0) {
		moduleObject.replyMail("reply", moduleObject.entryids[moduleObject.selectedMessages[0]]);
	}
}

function eventMailListReplyAll(moduleObject, element, event)
{
	if(moduleObject.selectedMessages.length > 0) {
		moduleObject.replyMail("replyall", moduleObject.entryids[moduleObject.selectedMessages[0]]);
	}
}

function eventMailListForwardMessage(moduleObject, element, event)
{
	if(moduleObject.selectedMessages.length > 0) {
		moduleObject.replyMail("forward", moduleObject.entryids[moduleObject.selectedMessages[0]]);
	}
}

function eventMailListContextMenuReply(moduleObject, element, event)
{
	element.parentNode.style.display = "none";
	moduleObject.replyMail("reply", moduleObject.entryids[moduleObject.selectedContextMessage]);
	
	eventListCheckSelectedContextMessage(this);
}

function eventMailListContextMenuReplyAll(moduleObject, element, event)
{
	element.parentNode.style.display = "none";
	moduleObject.replyMail("replyall", moduleObject.entryids[moduleObject.selectedContextMessage]);
	
	eventListCheckSelectedContextMessage(this);
}

function eventMailListContextMenuForward(moduleObject, element, event)
{
	element.parentNode.style.display = "none";
	moduleObject.replyMail("forward", moduleObject.entryids[moduleObject.selectedContextMessage]);
	
	eventListCheckSelectedContextMessage(this);
}

function eventMailListContextMenuMessageFlag(moduleObject, element, event)
{
	// hide context menu
	element.parentNode.style.display = "none";
	// get flag state
	var flag = "read";
	if(element.className.indexOf("unread") > 0) {
		flag = "unread";
	}
	// change flag
	var items = moduleObject.getSelectedMessages(element.parentNode.elementid);
	var flags = flag;
	for(i in items){
		if (flag=="read"){
			flags = "read,"+(moduleObject.sendReadReceipt(moduleObject.entryids[items[i]])?"receipt":"noreceipt");
		}else{
			flags = flag;
		}
		moduleObject.setReadFlag(moduleObject.entryids[items[i]], flags);
	}
	// deselect selected message
	eventListCheckSelectedContextMessage(this);
}

function eventMailListContextMenuRedFlag(moduleObject, element, event)
{
	element.parentNode.style.display = "none";
	var items = moduleObject.getSelectedMessages(element.parentNode.elementid);
	for(i in items){
		moduleObject.flagStatus(moduleObject.entryids[items[i]], 2, 6);
	}
	eventListCheckSelectedContextMessage(this);
}

function eventMailListContextMenuFlagComplete(moduleObject, element, event)
{
	element.parentNode.style.display = "none";
	var items = moduleObject.getSelectedMessages(element.parentNode.elementid);
	for(i in items){
		moduleObject.flagStatus(moduleObject.entryids[items[i]], 1, 0);
	}
	eventListCheckSelectedContextMessage(this);
}

function eventMailListContextMenuDeleteFlag(moduleObject, element, event)
{
	element.parentNode.style.display = "none";
	var items = moduleObject.getSelectedMessages(element.parentNode.elementid);
	for(i in items){
		moduleObject.flagStatus(moduleObject.entryids[items[i]], 0, 0);
	}
	eventListCheckSelectedContextMessage(this);
}

function eventMailListSearchBar(moduleObject, element, event)
{
	if (moduleObject.topElement.style.display=="none"){
		webclient.menu.toggleItem(element, true);
		webclient.settings.set("folders/entryid_"+moduleObject.entryid+"/searchbar/show", "true");
		moduleObject.topElement.style.display = "block";
	}else{
		webclient.menu.toggleItem(element, false);
		webclient.settings.set("folders/entryid_"+moduleObject.entryid+"/searchbar/show", "false");
		moduleObject.topElement.style.display = "none";

		// when there is a restriction active, remove it and reload maillist
		if (typeof moduleObject.filterRestriction != "undefined" && moduleObject.filterRestriction != false){
			eventMailListSearchBarClear(moduleObject, element, event);
		}
	}
	moduleObject.resize();
}

function eventMailListSearchBarFilterClick(moduleObject, element, event)
{
	var result = false;
	event.stopPropagation();
	if (!element.hasFocus){
		element.focus();
	}else{
		result = true;
	}
	return result;
}

function eventMailListSearchBarFilterFocus(moduleObject, element, event)
{
	element.hasFocus = (event.type=="focus")
}

function eventMailListSearchBarFilterMouseMove(moduleObject, element, event)
{
	event.stopPropagation();
	return element.hasFocus;
}

function eventMailListSearchBarFilterKey(moduleObject, element, event)
{
	moduleObject.topElement.clearButton.disabled = false;

	if (event.keyCode == 13){
		event.stopPropagation(); // stop other keyboard events
		eventMailListSearchBarSearch(moduleObject, element, event);
		return false;
	}
	return undefined;
}

function eventMailListSearchBarSearch(moduleObject, element, event)
{
	var input = moduleObject.topElement.filterInputbox;
	var target = moduleObject.topElement.filterTarget;
	var subfolders = moduleObject.topElement.searchSubfolders;
	if (input.value.trim() != ""){
		moduleObject.filterRestriction = input.value;
		moduleObject.filterRestrictionTarget = target.value;
		if (subfolders)
			moduleObject.searchSubfolders = subfolders.checked?"true":"false";
		else
			moduleObject.searchSubfolders = false;
		moduleObject.rowstart = 0;
		webclient.settings.set("folders/entryid_"+moduleObject.entryid+"/searchbar/target", target.selectedIndex);
		moduleObject.search();
		input.blur();
	}
}

function eventMailListSearchBarClear(moduleObject, element, event)
{
	moduleObject.stopSearch();
	var input = moduleObject.topElement.filterInputbox;
	input.value = "";
	moduleObject.filterRestriction = false;
	moduleObject.filterRestrictionTarget = false;
	moduleObject.rowstart = 0;
	moduleObject.list();
	moduleObject.topElement.clearButton.disabled = true;
	input.blur();
}

function eventMailListRules(moduleObject, element, event)
{
	webclient.openModalDialog(moduleObject, "rules", DIALOG_URL+"task=rules_modal&storeid=" + this.storeid, 500, 300);
}

/**
 * function for handle the restore button on main menu bar of folders.
 * @param object moduleObject Contains all the properties of a module object.
 * @param dom_element element The dom element's reference on which the event gets fired.
 * @param event event Event name
 * return - none, opens a dialog window.
 */
function eventRestoreItems(moduleObject, element, event){
	//task name should be "window.name _ standard" // as we are opening a standard dialog box.
	webclient.openWindow(
		moduleObject, 
		"restoreitems", 
		DIALOG_URL+"task=restoreitems_standard&storeid=" + this.storeid + "&parententryid=" + this.entryid,
		700, 500, false);
}

/**
 * function for sent the outbox mails and receive the new mail.
 * @param object moduleObject Contains all the properties of a module object.
 * @param dom_element element The dom element's reference on which the event gets fired.
 * @param event event Event name
 */
function eventSendReceiveItems(moduleObject, element, event){
	moduleObject.list();
}

