diff --git a/layouts/v7/modules/Settings/MailConverter/EditHeader.tpl b/layouts/v7/modules/Settings/MailConverter/EditHeader.tpl
index 2b9347b3cee37ac6fcdd28c398768796206e790b..d05fd4a0beba5e0d034b488646a234c079bd7091 100644
--- a/layouts/v7/modules/Settings/MailConverter/EditHeader.tpl
+++ b/layouts/v7/modules/Settings/MailConverter/EditHeader.tpl
@@ -1,12 +1,30 @@
-{*+**********************************************************************************
- * The contents of this file are subject to the vtiger CRM Public License Version 1.1
- * ("License"); You may not use this file except in compliance with the License
- * The Original Code is: vtiger CRM Open Source
- * The Initial Developer of the Original Code is vtiger.
- * Portions created by vtiger are Copyright (C) vtiger.
- * All Rights Reserved.
- ************************************************************************************}
-{* modules/Settings/MailConverter/views/Edit.php *}
-
-{* START YOUR IMPLEMENTATION FROM BELOW. Use {debug} for information *}
-<DIV>TEMPLATE: layout/modules/Settings/MailConverter/EditHeader.tpl</DIV>
+{*+**********************************************************************************
+* The contents of this file are subject to the vtiger CRM Public License Version 1.1
+* ("License"); You may not use this file except in compliance with the License
+* The Original Code is: vtiger CRM Open Source
+* The Initial Developer of the Original Code is vtiger.
+* Portions created by vtiger are Copyright (C) vtiger.
+* All Rights Reserved.
+************************************************************************************}
+
+{strip}
+	<div class="editViewPageDiv mailBoxEditDiv viewContent">
+		<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
+			<input type="hidden" id="create" value="{$CREATE}" />
+			<input type="hidden" id="recordId" value="{$RECORD_ID}" />
+			<input type="hidden" id="step" value="{$STEP}" />
+			<h4>
+				{if $CREATE eq 'new'}
+					{vtranslate('LBL_ADDING_NEW_MAILBOX',$QUALIFIED_MODULE)}
+				{else}
+					{vtranslate('LBL_EDIT_MAILBOX',$QUALIFIED_MODULE)}
+				{/if}
+			</h4>
+			<hr>
+			<div class="editViewContainer" style="padding-left: 2%;padding-right: 2%">
+				<div class="row">
+					{assign var=BREADCRUMB_LABELS value = ["step1" => "MAILBOX_DETAILS", "step2" => "SELECT_FOLDERS", "step3" => "ADD_RULES"]}
+					{include file="BreadCrumbs.tpl"|vtemplate_path:$QUALIFIED_MODULE ACTIVESTEP=1 BREADCRUMB_LABELS=$BREADCRUMB_LABELS MODULE=$QUALIFIED_MODULE}
+				</div>
+				<div class="clearfix"></div>
+{/strip}
\ No newline at end of file
diff --git a/layouts/v7/modules/Settings/MailConverter/EditRuleHeader.tpl b/layouts/v7/modules/Settings/MailConverter/EditRuleHeader.tpl
deleted file mode 100644
index 226db11bcbf33ef954f839b00c76e527fe8fa802..0000000000000000000000000000000000000000
--- a/layouts/v7/modules/Settings/MailConverter/EditRuleHeader.tpl
+++ /dev/null
@@ -1,12 +0,0 @@
-{*+**********************************************************************************
- * The contents of this file are subject to the vtiger CRM Public License Version 1.1
- * ("License"); You may not use this file except in compliance with the License
- * The Original Code is: vtiger CRM Open Source
- * The Initial Developer of the Original Code is vtiger.
- * Portions created by vtiger are Copyright (C) vtiger.
- * All Rights Reserved.
- ************************************************************************************}
-{* modules/Settings/MailConverter/views/EditRule.php *}
-
-{* START YOUR IMPLEMENTATION FROM BELOW. Use {debug} for information *}
-<DIV>TEMPLATE: layout/modules/Settings/MailConverter/EditRuleHeader.tpl</DIV>
diff --git a/layouts/v7/modules/Settings/MailConverter/Index.tpl b/layouts/v7/modules/Settings/MailConverter/Index.tpl
new file mode 100644
index 0000000000000000000000000000000000000000..6eae7fdbe0c5587aa5891df443894a650470799a
--- /dev/null
+++ b/layouts/v7/modules/Settings/MailConverter/Index.tpl
@@ -0,0 +1,8 @@
+{*+**********************************************************************************
+* The contents of this file are subject to the vtiger CRM Public License Version 1.1
+* ("License"); You may not use this file except in compliance with the License
+* The Original Code is: vtiger CRM Open Source
+* The Initial Developer of the Original Code is vtiger.
+* Portions created by vtiger are Copyright (C) vtiger.
+* All Rights Reserved.
+*************************************************************************************}
\ No newline at end of file
diff --git a/layouts/v7/modules/Settings/MailConverter/MapFields.tpl b/layouts/v7/modules/Settings/MailConverter/MapFields.tpl
deleted file mode 100644
index 63c9548c20ef39343164cb30d36ece96933364f6..0000000000000000000000000000000000000000
--- a/layouts/v7/modules/Settings/MailConverter/MapFields.tpl
+++ /dev/null
@@ -1,12 +0,0 @@
-{*+**********************************************************************************
- * The contents of this file are subject to the vtiger CRM Public License Version 1.1
- * ("License"); You may not use this file except in compliance with the License
- * The Original Code is: vtiger CRM Open Source
- * The Initial Developer of the Original Code is vtiger.
- * Portions created by vtiger are Copyright (C) vtiger.
- * All Rights Reserved.
- ************************************************************************************}
-{* modules/Settings/MailConverter/views/BodyAjax.php *}
-
-{* START YOUR IMPLEMENTATION FROM BELOW. Use {debug} for information *}
-<DIV>TEMPLATE: layout/modules/Settings/MailConverter/MapFields.tpl</DIV>
diff --git a/layouts/v7/modules/Settings/MailConverter/RuleEditView.tpl b/layouts/v7/modules/Settings/MailConverter/RuleEditView.tpl
new file mode 100644
index 0000000000000000000000000000000000000000..dcbc63bfe4508f7790183a0e4017152a69af57e8
--- /dev/null
+++ b/layouts/v7/modules/Settings/MailConverter/RuleEditView.tpl
@@ -0,0 +1,101 @@
+{*+**********************************************************************************
+* The contents of this file are subject to the vtiger CRM Public License Version 1.1
+* ("License"); You may not use this file except in compliance with the License
+* The Original Code is: vtiger CRM Open Source
+* The Initial Developer of the Original Code is vtiger.
+* Portions created by vtiger are Copyright (C) vtiger.
+* All Rights Reserved.
+*************************************************************************************}
+
+{strip}
+	<div class='modelContainer'>
+		<div class="modal-header contentsBackground">
+			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
+			<h3>{vtranslate('LBL_ADD_RULE', $QUALIFIED_MODULE)}</h3>
+		</div>
+		<form class="form-horizontal" id="ruleSave" method="post" action="index.php">
+			<input type="hidden" name="module" value="{$MODULE_NAME}" />
+			<input type="hidden" name="parent" value="Settings" />
+			<input type="hidden" name="action" value="SaveRule" />
+			<input type="hidden" name="scannerId" value="{$SCANNER_ID}" />
+			<input type="hidden" name="record" value="{$RECORD_ID}" />
+			<div class="modal-body tabbable">
+				{assign var=FIELDS value=$MODULE_MODEL->getSetupRuleFiels()}
+				{foreach key=FIELD_NAME item=FIELD_MODEL from=$FIELDS}
+					<div class="control-group">
+						<div class="control-label">
+							<label>
+								{vtranslate($FIELD_MODEL->get('label'),$QUALIFIED_MODULE)}
+							</label>
+						</div>
+						<div class="controls">
+							{assign var=FIELD_DATA_TYPE value=$FIELD_MODEL->getFieldDataType()}
+							{if $FIELD_DATA_TYPE eq 'picklist'}
+								{assign var=PICKLIST_VALUES value=$FIELD_MODEL->getPickListValues()}
+								{if $FIELD_NAME eq 'subject'}
+									<select name="subjectop" class="chzn-select" style="min-width:220px">
+										<option value="">{vtranslate('LBL_SELECT_OPTION',$QUALIFIED_MODULE)}</option>
+										{foreach key=PICKLIST_KEY item=PICKLIST_VALUE from=$PICKLIST_VALUES}
+											<option value="{$PICKLIST_KEY}" {if $RECORD_MODEL->get('subjectop') eq $PICKLIST_KEY} selected {/if} >{$PICKLIST_VALUE}</option>
+										{/foreach}
+									</select>&nbsp;&nbsp;
+									<input type="text" name="{$FIELD_MODEL->getName()}" value="{$RECORD_MODEL->get($FIELD_NAME)}" />
+								{elseif $FIELD_NAME eq 'body'}
+									<select name="bodyop" class="chzn-select" style="min-width:220px">
+										<option value="" {if $RECORD_MODEL->get('bodyop') eq ""}selected{/if}>{vtranslate('LBL_SELECT_OPTION',$QUALIFIED_MODULE)}</option>
+										{foreach key=PICKLIST_KEY item=PICKLIST_VALUE from=$PICKLIST_VALUES}
+											<option value="{$PICKLIST_KEY}" {if $RECORD_MODEL->get('bodyop') eq $PICKLIST_KEY} selected {/if} >{$PICKLIST_VALUE}</option>
+										{/foreach}
+									</select>&nbsp;&nbsp;
+									<br><br>
+									<textarea name="{$FIELD_MODEL->getName()}">{$RECORD_MODEL->get($FIELD_NAME)}</textarea>
+								{else}
+									<select id="actions" name="action1" class="select2" style="min-width:220px">
+										{foreach key=PICKLIST_KEY item=PICKLIST_VALUE from=$PICKLIST_VALUES}
+											<option value="{$PICKLIST_KEY}" {if $RECORD_MODEL->get($FIELD_NAME) eq $PICKLIST_KEY} selected {/if} >{$PICKLIST_VALUE}</option>
+										{/foreach}
+									</select>
+								{/if}
+							{elseif $FIELD_DATA_TYPE eq 'radio'}
+								{assign var=RADIO_OPTIONS value=$FIELD_MODEL->getRadioOptions()}
+								{foreach key=RADIO_NAME item=RADIO_VALUE from=$RADIO_OPTIONS}
+									<label class="radio inline">
+										<input class="radio" type="radio" name="{$FIELD_MODEL->getName()}" value="{$RADIO_NAME}" 
+											{if empty($RECORD_ID) && ($RADIO_NAME eq 'AND')} checked="" {/if} {if $RECORD_MODEL->get($FIELD_NAME) eq $RADIO_NAME} checked {/if} />
+										{$RADIO_VALUE}
+									</label>
+								{/foreach}
+							{elseif $FIELD_DATA_TYPE eq 'email'}
+								<input type="text" name="{$FIELD_MODEL->getName()}" value="{$RECORD_MODEL->get($FIELD_NAME)}" data-validation-engine="validate[funcCall[Vtiger_Email_Validator_Js.invokeValidation]]"/>
+							{else}
+								<input type="text" name="{$FIELD_MODEL->getName()}" value="{$RECORD_MODEL->get($FIELD_NAME)}"/>
+							{/if}	
+						</div>
+					</div>	
+				{/foreach}
+				<div style="" id="assignedToBlock" {if $RECORD_MODEL->get('action') eq 'UPDATE_HelpDesk_SUBJECT'}class="hide"{/if}>
+					<div class="control-label">
+						<label>{vtranslate('Assigned To')}</label>
+					</div>
+					<div class="controls">
+						<select class="select2-container select2" id="assignedTo" name="assignedTo" style="width: 49%;">
+							<optgroup label="{vtranslate('LBL_USERS')}">
+								{assign var=USERS value=$USER_MODEL->getAccessibleUsersForModule($MODULE_NAME)}
+								{foreach key=OWNER_ID item=OWNER_NAME from=$USERS}
+									<option value="{$OWNER_ID}" data-picklistvalue= '{$OWNER_NAME}' {if $ASSIGNED_USER eq $OWNER_ID} selected {/if}>{$OWNER_NAME}</option>
+								{/foreach}
+							</optgroup>
+							<optgroup label="{vtranslate('LBL_GROUPS')}">
+								{assign var=GROUPS value=$USER_MODEL->getAccessibleGroups()}	
+								{foreach key=OWNER_ID item=OWNER_NAME from=$GROUPS}
+									<option value="{$OWNER_ID}" data-picklistvalue= '{$OWNER_NAME}' {if $ASSIGNED_USER eq $OWNER_ID} selected {/if}>{$OWNER_NAME}</option>
+								{/foreach}
+							</optgroup>
+						</select>
+					</div>
+				</div>
+			</div>
+			{include file='ModalFooter.tpl'|@vtemplate_path:$QUALIFIED_MODULE}
+		</form>
+	</div>
+{/strip}
diff --git a/layouts/v7/modules/Settings/MailConverter/RuleStep1.tpl b/layouts/v7/modules/Settings/MailConverter/RuleStep1.tpl
deleted file mode 100644
index 16e20762ea8c97c87395388ac38abe481f2c04df..0000000000000000000000000000000000000000
--- a/layouts/v7/modules/Settings/MailConverter/RuleStep1.tpl
+++ /dev/null
@@ -1,12 +0,0 @@
-{*+**********************************************************************************
- * The contents of this file are subject to the vtiger CRM Public License Version 1.1
- * ("License"); You may not use this file except in compliance with the License
- * The Original Code is: vtiger CRM Open Source
- * The Initial Developer of the Original Code is vtiger.
- * Portions created by vtiger are Copyright (C) vtiger.
- * All Rights Reserved.
- ************************************************************************************}
-{* modules/Settings/MailConverter/views/EditRule.php *}
-
-{* START YOUR IMPLEMENTATION FROM BELOW. Use {debug} for information *}
-<DIV>TEMPLATE: layout/modules/Settings/MailConverter/RuleStep1.tpl</DIV>
diff --git a/layouts/v7/modules/Settings/MailConverter/RuleStep2.tpl b/layouts/v7/modules/Settings/MailConverter/RuleStep2.tpl
deleted file mode 100644
index 2caf4bd5ad38c2f4f69eece3663b6a093d484749..0000000000000000000000000000000000000000
--- a/layouts/v7/modules/Settings/MailConverter/RuleStep2.tpl
+++ /dev/null
@@ -1,12 +0,0 @@
-{*+**********************************************************************************
- * The contents of this file are subject to the vtiger CRM Public License Version 1.1
- * ("License"); You may not use this file except in compliance with the License
- * The Original Code is: vtiger CRM Open Source
- * The Initial Developer of the Original Code is vtiger.
- * Portions created by vtiger are Copyright (C) vtiger.
- * All Rights Reserved.
- ************************************************************************************}
-{* modules/Settings/MailConverter/views/EditRule.php *}
-
-{* START YOUR IMPLEMENTATION FROM BELOW. Use {debug} for information *}
-<DIV>TEMPLATE: layout/modules/Settings/MailConverter/RuleStep2.tpl</DIV>
diff --git a/layouts/v7/modules/Settings/MailConverter/Step1.tpl b/layouts/v7/modules/Settings/MailConverter/Step1.tpl
index cd7f643bac6b1fcb559ce8be1238b8a7a9d5058b..c2b8c893735b5a19229ad871c7f9408e8f71f3e3 100644
--- a/layouts/v7/modules/Settings/MailConverter/Step1.tpl
+++ b/layouts/v7/modules/Settings/MailConverter/Step1.tpl
@@ -1,12 +1,101 @@
 {*+**********************************************************************************
- * The contents of this file are subject to the vtiger CRM Public License Version 1.1
- * ("License"); You may not use this file except in compliance with the License
- * The Original Code is: vtiger CRM Open Source
- * The Initial Developer of the Original Code is vtiger.
- * Portions created by vtiger are Copyright (C) vtiger.
- * All Rights Reserved.
- ************************************************************************************}
-{* modules/Settings/MailConverter/views/Edit.php *}
+* The contents of this file are subject to the vtiger CRM Public License Version 1.1
+* ("License"); You may not use this file except in compliance with the License
+* The Original Code is: vtiger CRM Open Source
+* The Initial Developer of the Original Code is vtiger.
+* Portions created by vtiger are Copyright (C) vtiger.
+* All Rights Reserved.
+************************************************************************************}
 
-{* START YOUR IMPLEMENTATION FROM BELOW. Use {debug} for information *}
-<DIV>TEMPLATE: layout/modules/Settings/MailConverter/Step1.tpl</DIV>
+{strip}
+	<div class="block fieldBlockContainer">
+		<form class="form-horizontal" id="mailBoxEditView" name="step1">
+			{assign var=FIELDS value=$MODULE_MODEL->getFields()}
+			{if empty($RECORD_ID)}
+				{assign var=RECORD_EXISTS value=false}
+			{else}
+				{assign var=RECORD_EXISTS value=true}
+			{/if}
+
+			{if $RECORD_EXISTS}
+				<input type="hidden" name="record" value="{$RECORD_MODEL->getId()}" />
+				<input type="hidden" name="scannerOldName" value="{$RECORD_MODEL->getName()}" />
+			{/if}
+			<div class="addMailBoxStep">
+				<div class="row">
+					<table class="table editview-table no-border">
+						<tbody>
+							{foreach key=FIELD_NAME item=FIELD_MODEL from=$FIELDS}
+								{if !$RECORD_MODEL->isFieldEditable($FIELD_MODEL)}
+									{continue}
+								{/if}
+								<tr>
+									<td class="fieldLabel" style="width:20%;"><label>{vtranslate($FIELD_MODEL->get('label'),$QUALIFIED_MODULE)}</label></td>
+									<td class="fieldValue">
+										{assign var=FIELD_DATA_TYPE value=$FIELD_MODEL->getFieldDataType()}
+										{if $FIELD_DATA_TYPE eq 'password'}
+											<input class="inputElement" type="password" name="{$FIELD_MODEL->getName()}" {if $RECORD_EXISTS} value="{$RECORD_MODEL->get($FIELD_NAME)}" {/if}
+												{if $FIELD_MODEL->isMandatory()}data-validation-engine="validate[required]"{/if} />
+										{elseif $FIELD_DATA_TYPE eq 'boolean'}
+											{assign var=RECORD_ID value=$RECORD_MODEL->getId()}
+											<input type="hidden" name="{$FIELD_MODEL->getName()}" value="0" />
+											<input type="checkbox" name="{$FIELD_MODEL->getName()}" {if ($RECORD_MODEL->get($FIELD_MODEL->getName()) eq '1') || (empty($RECORD_ID))}checked{/if} />
+										{elseif $FIELD_DATA_TYPE eq 'picklist'}
+											{assign var=PICKLIST_VALUES value=$FIELD_MODEL->getPickListValues()}
+											{assign var=FIELD_VALUE value=$RECORD_MODEL->get($FIELD_NAME)}
+											{if $FIELD_MODEL->getName() eq 'time_zone' && empty($FIELD_VALUE)}
+												{assign var=FIELD_VALUE value=" "}
+											{/if}
+											<select name="{$FIELD_MODEL->getName()}" class="select2 inputElement"
+												{* to show dropdown above *}
+												{if $FIELD_MODEL->getName() eq 'time_zone'}
+													data-dropdownCssClass="select2-drop-above"
+												{/if}
+												>
+												{if $FIELD_MODEL->getName() eq 'time_zone'}
+													{* since in time zone its array of value and key, since there will mutiple areas with same time_zone *}
+													{foreach item=PICKLIST_VALUE key=PICKLIST_KEY from=$PICKLIST_VALUES}
+														<option value="{$PICKLIST_KEY}" {if $FIELD_VALUE eq $PICKLIST_KEY} selected {/if} >{vtranslate($PICKLIST_VALUE,$QUALIFIED_MODULE)}</option>
+													{/foreach}
+												{else}
+													{foreach key=PICKLIST_KEY item=PICKLIST_VALUE from=$PICKLIST_VALUES}
+														<option value="{$PICKLIST_KEY}" {if $RECORD_MODEL->get($FIELD_NAME) eq $PICKLIST_KEY} selected {/if} >{$PICKLIST_VALUE}</option>
+													{/foreach}
+												{/if}
+											</select>
+										{elseif $FIELD_DATA_TYPE eq 'radio'}
+											{assign var=RADIO_OPTIONS value=$FIELD_MODEL->getRadioOptions()}
+											{foreach key=RADIO_NAME item=RADIO_VALUE from=$RADIO_OPTIONS}
+												<label class="radioOption inline">
+													<input class="radioOption" type="radio" name="{$FIELD_MODEL->getName()}" value="{$RADIO_NAME}" 
+														{if $RECORD_EXISTS}
+															{if $RECORD_MODEL->get($FIELD_NAME) eq $RADIO_NAME} checked {/if}
+														{else}
+															{if $RADIO_NAME eq 'imap4' || $RADIO_NAME eq 'ssl' || $RADIO_NAME eq 'novalidate-cert'} checked {/if} 
+														{/if} />&nbsp;
+													{$RADIO_VALUE}
+												</label>&nbsp;&nbsp;&nbsp;&nbsp;
+											{/foreach}
+										{else}
+											<input type="text" class="inputElement" name="{$FIELD_MODEL->getName()}" {if $FIELD_MODEL->isMandatory()}data-validation-engine="validate[required]"{/if} value="{$RECORD_MODEL->get($FIELD_NAME)}"/>
+										{/if}
+									</td>
+								</tr>
+							{/foreach}
+						</tbody>
+					</table>
+				</div>
+			</div>
+			<div class="border1px modal-overlay-footer clearfix">
+				<div class="row clearfix">
+					<div class="textAlignCenter col-lg-12 col-md-12 col-lg-12 ">
+						<button type="submit" class="btn btn-success nextStep" onclick="javascript:Settings_MailConverter_Edit_Js.firstStep()">{vtranslate('LBL_NEXT',$MODULE)}</button>&nbsp;&nbsp;
+						<a type="reset" class="cancelLink cursorPointer" onclick="javascript:window.history.back();">{vtranslate('LBL_CANCEL',$MODULE)}</a>
+					</div>
+				</div>
+			</div>
+		</form>
+	</div>
+</div>
+</div>
+{/strip}
\ No newline at end of file
diff --git a/layouts/v7/modules/Settings/MailConverter/Step2.tpl b/layouts/v7/modules/Settings/MailConverter/Step2.tpl
index 5e4e277a496e4536686faceebc17f6cc968c965d..aadb8ac97c40ecacc2bafb0bd00742e75e29fea1 100644
--- a/layouts/v7/modules/Settings/MailConverter/Step2.tpl
+++ b/layouts/v7/modules/Settings/MailConverter/Step2.tpl
@@ -6,7 +6,52 @@
  * Portions created by vtiger are Copyright (C) vtiger.
  * All Rights Reserved.
  ************************************************************************************}
-{* modules/Settings/MailConverter/views/Edit.php *}
 
-{* START YOUR IMPLEMENTATION FROM BELOW. Use {debug} for information *}
-<DIV>TEMPLATE: layout/modules/Settings/MailConverter/Step2.tpl</DIV>
+{strip}
+	{if $IMAP_ERROR || $CONNECTION_ERROR}
+		<div class="block">
+			<strong>
+				{if $IMAP_ERROR}
+					{$IMAP_ERROR}
+				{else if $CONNECTION_ERROR}
+					{vtranslate('LBL_CONNECTION_ERROR',$QUALIFIED_MODULE)}
+				{/if}
+			</strong>
+		</div>
+		<br>
+	{/if}
+	<div class="addMailBoxBlock">
+		<div class="row col-lg-12 padding-bottom1per">
+			<div id="mailConverterDragIcon"><i class="icon-info-sign"></i>&nbsp;&nbsp;{vtranslate('TO_CHANGE_THE_FOLDER_SELECTION_DESELECT_ANY_OF_THE_SELECTED_FOLDERS',$QUALIFIED_MODULE)}</div>
+		</div>
+		<br>
+		<br>
+		<form class="form-horizontal" id="mailBoxEditView" name="step2">
+			<div class="block">
+				<div class="addMailBoxStep row">
+					{foreach key=FOLDER item=SELECTED from=$FOLDERS}
+						<div class="col-lg-3">
+							<input type="checkbox" name="folders" value="{$FOLDER}" {if $SELECTED eq 'checked'}checked{/if}>
+							&nbsp;&nbsp;&nbsp;{$FOLDER}
+						</div>
+					{/foreach}
+				</div>
+				<div class="border1px modal-overlay-footer clearfix">
+					<div class="row clearfix">
+						<div class="textAlignCenter col-lg-12 col-md-12 col-lg-12 ">
+							<button class="btn btn-danger backStep" type="button" onclick="javascript:window.history.back();"><strong>{vtranslate('LBL_BACK', $QUALIFIED_MODULE)}</strong></button>&nbsp;&nbsp;
+							<button class="btn btn-success" onclick="javascript:Settings_MailConverter_Edit_Js.secondStep()">
+								<strong>
+									{if $CREATE eq 'new'}{vtranslate('LBL_NEXT', $QUALIFIED_MODULE)}{else}{vtranslate('LBL_FINISH', $QUALIFIED_MODULE)}{/if}
+								</strong>
+							</button>
+							<a class="cancelLink" type="reset" onclick="javascript:window.history.go(-2);">{vtranslate('LBL_CANCEL', $QUALIFIED_MODULE)}</a>
+						</div>
+					</div>
+				</div>
+			</div>
+		</form>
+	</div>
+</div>
+</div>
+{/strip}
\ No newline at end of file
diff --git a/layouts/v7/modules/Settings/MailConverter/Step3.tpl b/layouts/v7/modules/Settings/MailConverter/Step3.tpl
new file mode 100644
index 0000000000000000000000000000000000000000..277d1c88c2d44794efec7553989585d884aa0b46
--- /dev/null
+++ b/layouts/v7/modules/Settings/MailConverter/Step3.tpl
@@ -0,0 +1,110 @@
+{*+**********************************************************************************
+* The contents of this file are subject to the vtiger CRM Public License Version 1.1
+* ("License"); You may not use this file except in compliance with the License
+* The Original Code is: vtiger CRM Open Source
+* The Initial Developer of the Original Code is vtiger.
+* Portions created by vtiger are Copyright (C) vtiger.
+* All Rights Reserved.
+*************************************************************************************}
+
+{strip}
+	<div class="block fieldBlockContainer">
+		<form class="form-horizontal" id="ruleSave" method="post" name="step3">
+			<input type="hidden" name="module" value="{$MODULE_NAME}" />
+			<input type="hidden" name="parent" value="Settings" />
+			<input type="hidden" name="action" value="SaveRule" />
+			<input type="hidden" name="scannerId" value="{$SCANNER_ID}" />
+			<input type="hidden" name="record" value="{$RECORD_ID}" />
+			<div class="addMailBoxStep">
+				<div class="row">
+					<table class="table editview-table no-border">
+						<tbody>
+							{assign var=FIELDS value=$MODULE_MODEL->getSetupRuleFiels()}
+							{foreach key=FIELD_NAME item=FIELD_MODEL from=$FIELDS}
+								<tr>
+									<td class="fieldLabel" style="width:20%;"><label>{vtranslate($FIELD_MODEL->get('label'),$QUALIFIED_MODULE)}</label></td>
+									<td class="fieldValue">
+										{assign var=FIELD_DATA_TYPE value=$FIELD_MODEL->getFieldDataType()}
+										{if $FIELD_DATA_TYPE eq 'picklist'}
+											{assign var=PICKLIST_VALUES value=$FIELD_MODEL->getPickListValues()}
+											{if $FIELD_NAME eq 'subject'}
+												<select name="subjectop" class="select2 inputElement">
+													<option value="">{vtranslate('LBL_SELECT_OPTION',$QUALIFIED_MODULE)}</option>
+													{foreach key=PICKLIST_KEY item=PICKLIST_VALUE from=$PICKLIST_VALUES}
+														<option value="{$PICKLIST_KEY}" {if $RECORD_MODEL->get('subjectop') eq $PICKLIST_KEY} selected {/if} >{$PICKLIST_VALUE}</option>
+													{/foreach}
+												</select>&nbsp;&nbsp;
+												<input type="text" class="inputElement" name="{$FIELD_MODEL->getName()}" value="{$RECORD_MODEL->get($FIELD_NAME)}" style="margin-left: 10px;" />
+											{elseif $FIELD_NAME eq 'body'}
+												<select name="bodyop" class="select2 inputElement">
+													<option value="" {if $RECORD_MODEL->get('bodyop') eq ""}selected{/if}>{vtranslate('LBL_SELECT_OPTION',$QUALIFIED_MODULE)}</option>
+													{foreach key=PICKLIST_KEY item=PICKLIST_VALUE from=$PICKLIST_VALUES}
+														<option value="{$PICKLIST_KEY}" {if $RECORD_MODEL->get('bodyop') eq $PICKLIST_KEY} selected {/if} >{$PICKLIST_VALUE}</option>
+													{/foreach}
+												</select>&nbsp;&nbsp;
+												<br><br>
+												<textarea name="{$FIELD_MODEL->getName()}" class="boxSizingBorderBox inputElement" style="width:416px;padding: 3px 8px;">{$RECORD_MODEL->get($FIELD_NAME)}</textarea>
+											{else}
+												<select id="actions" name="action1" class="select2 inputElement" style="min-width:220px">
+													{foreach key=PICKLIST_KEY item=PICKLIST_VALUE from=$PICKLIST_VALUES}
+														<option value="{$PICKLIST_KEY}" {if $RECORD_MODEL->get($FIELD_NAME) eq $PICKLIST_KEY} selected {/if} >{$PICKLIST_VALUE}</option>
+													{/foreach}
+												</select>
+											{/if}
+										{elseif $FIELD_DATA_TYPE eq 'radio'}
+											{assign var=RADIO_OPTIONS value=$FIELD_MODEL->getRadioOptions()}
+											{foreach key=RADIO_NAME item=RADIO_VALUE from=$RADIO_OPTIONS}
+												<label class="radioOption inline">
+													<input class="radioOption" type="radio" name="{$FIELD_MODEL->getName()}" value="{$RADIO_NAME}" {if $DEFAULT_MATCH eq $RADIO_NAME} checked {/if} />
+													{$RADIO_VALUE}
+												</label>&nbsp;&nbsp;&nbsp;&nbsp;
+											{/foreach}
+										{elseif $FIELD_DATA_TYPE eq 'email'}
+											<input type="text" class="inputElement" name="{$FIELD_MODEL->getName()}" value="{$RECORD_MODEL->get($FIELD_NAME)}" data-validation-engine="validate[funcCall[Vtiger_Email_Validator_Js.invokeValidation]]"/>
+										{else}
+											<input type="text" class="inputElement" name="{$FIELD_MODEL->getName()}" value="{$RECORD_MODEL->get($FIELD_NAME)}"/>
+										{/if}
+									</td>
+								</tr>
+							{/foreach}
+							<tr>
+								<td class="fieldLabel" style="width:20%;"><label>{vtranslate('Assigned To')}</label></td>
+								<td class="fieldValue">
+									<select class="select2 inputElement" id="assignedTo" name="assignedTo">
+										<optgroup label="{vtranslate('LBL_USERS')}">
+											{assign var=USERS value=$USER_MODEL->getAccessibleUsersForModule($MODULE_NAME)}
+											{foreach key=OWNER_ID item=OWNER_NAME from=$USERS}
+												<option value="{$OWNER_ID}" data-picklistvalue= '{$OWNER_NAME}' {if $ASSIGNED_USER eq $OWNER_ID} selected {/if}>
+													{$OWNER_NAME}
+												</option>
+											{/foreach}
+										</optgroup>
+										<optgroup label="{vtranslate('LBL_GROUPS')}">
+											{assign var=GROUPS value=$USER_MODEL->getAccessibleGroups()}	
+											{foreach key=OWNER_ID item=OWNER_NAME from=$GROUPS}
+												<option value="{$OWNER_ID}" data-picklistvalue= '{$OWNER_NAME}' {if $ASSIGNED_USER eq $OWNER_ID} selected {/if}>
+													{$OWNER_NAME}
+												</option>
+											{/foreach}
+										</optgroup>
+									</select>
+								</td>
+							</tr>
+						</tbody>
+					</table>
+				</div>
+			</div>
+			<div class="border1px modal-overlay-footer clearfix">
+				<div class="row clearfix">
+					<div class="textAlignCenter col-lg-12 col-md-12 col-lg-12 ">
+						<button class="btn btn-danger backStep" type="button" onclick="javascript:window.history.back();"><strong>{vtranslate('LBL_BACK', $QUALIFIED_MODULE)}</strong></button>&nbsp;&nbsp;
+						<button class="btn btn-success" onclick="javascript:Settings_MailConverter_Edit_Js.thirdStep()"><strong>{vtranslate('LBL_FINISH', $QUALIFIED_MODULE)}</strong></button>
+						<a class="cancelLink" type="reset" onclick="javascript:window.history.go(-3);">{vtranslate('LBL_CANCEL', $QUALIFIED_MODULE)}</a>
+					</div>
+				</div>
+			</div>
+		</form>
+	</div>
+</div>
+</div>
+{/strip}
\ No newline at end of file
diff --git a/layouts/v7/modules/Settings/Vtiger/ConfigEditorEdit.tpl b/layouts/v7/modules/Settings/Vtiger/ConfigEditorEdit.tpl
index 3906d53291bfe5a9bf6cf639e6656f51add9fa00..084309c97eeff789645e4811ccf32e049ca08f3e 100644
--- a/layouts/v7/modules/Settings/Vtiger/ConfigEditorEdit.tpl
+++ b/layouts/v7/modules/Settings/Vtiger/ConfigEditorEdit.tpl
@@ -7,76 +7,78 @@
 * All Rights Reserved.
 ************************************************************************************}
 {strip}
-    <div class="editViewPageDiv " id="editViewContent">
-        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 ">
-            <div class="contents">
-                <form id="ConfigEditorForm" class="form-horizontal" data-detail-url="{$MODEL->getDetailViewUrl()}" method="POST">
-                    {assign var=WIDTHTYPE value=$CURRENT_USER_MODEL->get('rowheight')}
-                    {assign var=FIELD_VALIDATION  value=['HELPDESK_SUPPORT_EMAIL_ID' => 'data-rule-email="true"',
-                                                                    'upload_maxsize' => 'data-rule-range=[1,5] data-rule-positive="true" data-rule-wholeNumber="true"',
-                                                                'history_max_viewed' => 'data-rule-range=[1,5] data-rule-positive="true" data-rule-wholeNumber="true"',
-                                                           'listview_max_textlength' => 'data-rule-range=[1,100] data-rule-positive="true" data-rule-wholeNumber="true"',
-                                                         'list_max_entries_per_page' => 'data-rule-range=[1,100] data-rule-positive="true" data-rule-wholeNumber="true"']}
+	<div class="editViewPageDiv " id="editViewContent">
+		<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 ">
+			<div class="contents">
+				<form id="ConfigEditorForm" class="form-horizontal" data-detail-url="{$MODEL->getDetailViewUrl()}" method="POST">
+					{assign var=WIDTHTYPE value=$CURRENT_USER_MODEL->get('rowheight')}
+					{assign var=FIELD_VALIDATION  value=['HELPDESK_SUPPORT_EMAIL_ID'	=> 'data-rule-email="true"',
+																	'upload_maxsize'	=> 'data-rule-range=[1,5] data-rule-positive="true" data-rule-wholeNumber="true"',
+																'history_max_viewed'	=> 'data-rule-range=[1,5] data-rule-positive="true" data-rule-wholeNumber="true"',
+															'listview_max_textlength'	=> 'data-rule-range=[1,100] data-rule-positive="true" data-rule-wholeNumber="true"',
+															'list_max_entries_per_page'	=> 'data-rule-range=[1,100] data-rule-positive="true" data-rule-wholeNumber="true"']}
 
-                    <div>
-                        <h4>{vtranslate('LBL_CONFIG_EDITOR', $QUALIFIED_MODULE)}</h4>
-                    </div>
-                    <hr>    
-                    <br>
-                    <div class="detailViewInfo">
-                        {assign var=FIELD_DATA value=$MODEL->getViewableData()}
-                        {foreach key=FIELD_NAME item=FIELD_DETAILS from=$MODEL->getEditableFields()}
-                            <div class="row form-group">
-                                <div class="col-lg-4 control-label fieldLabel">
-                                    <label>{if $FIELD_NAME == 'upload_maxsize'}{if $FIELD_DATA[$FIELD_NAME] gt 5}{vtranslate($FIELD_DETAILS['label'], $QUALIFIED_MODULE,$FIELD_DATA[$FIELD_NAME])}{else}{vtranslate($FIELD_DETAILS['label'], $QUALIFIED_MODULE,5)}{/if}{else}{vtranslate($FIELD_DETAILS['label'], $QUALIFIED_MODULE)}{/if}</label>
-                                </div>
-                                <div  class="{$WIDTHTYPE}  col-lg-4 input-group">
-                                    {if $FIELD_DETAILS['fieldType'] == 'picklist'}
+					<div>
+						<h4>{vtranslate('LBL_CONFIG_EDITOR', $QUALIFIED_MODULE)}</h4>
+					</div>
+					<hr>
+					<br>
+					<div class="detailViewInfo">
+						{assign var=FIELD_DATA value=$MODEL->getViewableData()}
+						{foreach key=FIELD_NAME item=FIELD_DETAILS from=$MODEL->getEditableFields()}
+							<div class="row form-group">
+								<div class="col-lg-4 control-label fieldLabel">
+									<label>{if $FIELD_NAME == 'upload_maxsize'}{if $FIELD_DATA[$FIELD_NAME] gt 5}{vtranslate($FIELD_DETAILS['label'], $QUALIFIED_MODULE,$FIELD_DATA[$FIELD_NAME])}{else}{vtranslate($FIELD_DETAILS['label'], $QUALIFIED_MODULE,5)}{/if}{else}{vtranslate($FIELD_DETAILS['label'], $QUALIFIED_MODULE)}{/if}</label>
+								</div>
+								<div  class="{$WIDTHTYPE}  col-lg-4 input-group">
+									{if $FIELD_DETAILS['fieldType'] == 'picklist'}
 
-                                        <select class="select2-container inputElement select2 col-lg-11" name="{$FIELD_NAME}" >
-                                            {foreach key=optionName item=optionLabel from=$MODEL->getPicklistValues($FIELD_NAME)}
-                                                {if $FIELD_NAME != 'default_module' && $FIELD_NAME != 'default_reply_to'}
-                                                    <option {if $optionLabel == $FIELD_DATA[$FIELD_NAME]} selected {/if}>{vtranslate($optionLabel, $QUALIFIED_MODULE)}</option>
-                                                {else if $FIELD_NAME == 'default_reply_to'}
-                                                    <option value="{$optionName}" {if $optionName == $FIELD_DATA[$FIELD_NAME]} selected {/if}>{vtranslate($optionName)}</option>
-                                                {else}
-                                                    <option value="{$optionName}" {if $optionLabel == $FIELD_DATA[$FIELD_NAME]} selected {/if}>{vtranslate($optionLabel, $optionLabel)}</option>
-                                                {/if}
-                                            {/foreach}
-                                        </select>
-                                        {if $FIELD_NAME == 'default_reply_to'}
-                                            <div class="input-group-addon input-select-addon"><i class="fa fa-info-circle" data-toggle="tooltip" data-placement="right" title="{vtranslate('LBL_DEFAULT_REPLY_TO_INFO',$QUALIFIED_MODULE)}"></i></div>
-                                            {/if}
+										<select class="select2-container inputElement select2 col-lg-11" name="{$FIELD_NAME}" >
+											{foreach key=optionName item=optionLabel from=$MODEL->getPicklistValues($FIELD_NAME)}
+												{if $FIELD_NAME != 'default_module' && $FIELD_NAME != 'default_reply_to'}
+													<option {if $optionLabel == $FIELD_DATA[$FIELD_NAME]} selected {/if}>{vtranslate($optionLabel, $QUALIFIED_MODULE)}</option>
+												{else if $FIELD_NAME == 'default_reply_to'}
+													<option value="{$optionName}" {if $optionName == $FIELD_DATA[$FIELD_NAME]} selected {/if}>{vtranslate($optionName)}</option>
+												{else}
+													<option value="{$optionName}" {if $optionLabel == $FIELD_DATA[$FIELD_NAME]} selected {/if}>{vtranslate($optionLabel, $optionLabel)}</option>
+												{/if}
+											{/foreach}
+										</select>
+										{if $FIELD_NAME == 'default_reply_to'}
+											<div class="input-group-addon input-select-addon"><i class="fa fa-info-circle" data-toggle="tooltip" data-placement="right" title="{vtranslate('LBL_DEFAULT_REPLY_TO_INFO',$QUALIFIED_MODULE)}"></i></div>
+										{/if}
 
-                                    {else if $FIELD_NAME == 'USE_RTE'}
-                                        <input type="hidden" name="{$FIELD_NAME}" value="false" />
-                                        <div class=" "> <input type="checkbox" name="{$FIELD_NAME}" value="true" {if $FIELD_DATA[$FIELD_NAME] == 'true'} checked {/if} /></div>
-                                    {else if $FIELD_NAME == 'email_tracking'}
-                                        <input type="hidden" name="{$FIELD_NAME}" value="No" />
-                                        <input type="checkbox" name="{$FIELD_NAME}" value="Yes" {if $FIELD_DATA[$FIELD_NAME] == "Yes"} checked {/if} />
-                                        <div class="input-info-addon"> <i class="fa fa-question-circle"  data-toggle="tooltip" data-placement="right" title="{vtranslate('LBL_PERSONAL_EMAIL_TRACKING_INFO',$QUALIFIED_MODULE)}"></i>
-                                        </div>
-                                    {else}
-                                        <div class=" input-group inputElement"> 
-                                            <input type="text" class="inputElement "  name="{$FIELD_NAME}" data-rule-required="true" {if $FIELD_VALIDATION[$FIELD_NAME]} {$FIELD_VALIDATION[$FIELD_NAME]} {/if} value="{$FIELD_DATA[$FIELD_NAME]}" />
-                                            {if $FIELD_NAME == 'upload_maxsize'}
-                                                <div class="input-group-addon">{vtranslate('LBL_MB', $QUALIFIED_MODULE)}</div>{/if}
-                                            </div>
-                                        {/if}
-                                    </div></div>
-                                    {/foreach}
-                                </div>
-                                <div class='modal-overlay-footer clearfix'>
-                                    <div class=" row clearfix">
-                                        <div class=' textAlignCenter col-lg-12 col-md-12 col-sm-12 '>
-                                            <button type='submit' class='btn btn-success saveButton'  >{vtranslate('LBL_SAVE', $MODULE)}</button>&nbsp;&nbsp;
-                                            <a class='cancelLink' type="reset">{vtranslate('LBL_CANCEL', $MODULE)}</a>
-                                        </div>
-                                    </div>
-                                </div>
-                            </form>
-                        </div>
-                    </div>
-                </div>
-                {/strip}
+									{else if $FIELD_NAME == 'USE_RTE'}
+										<input type="hidden" name="{$FIELD_NAME}" value="false" />
+										<div class=" "> <input type="checkbox" name="{$FIELD_NAME}" value="true" {if $FIELD_DATA[$FIELD_NAME] == 'true'} checked {/if} /></div>
+										{else if $FIELD_NAME == 'email_tracking'}
+										<input type="hidden" name="{$FIELD_NAME}" value="No" />
+										<input type="checkbox" name="{$FIELD_NAME}" value="Yes" {if $FIELD_DATA[$FIELD_NAME] == "Yes"} checked {/if} />
+										<div class="input-info-addon"> <i class="fa fa-question-circle"  data-toggle="tooltip" data-placement="right" title="{vtranslate('LBL_PERSONAL_EMAIL_TRACKING_INFO',$QUALIFIED_MODULE)}"></i>
+										</div>
+									{else}
+										<div class=" input-group inputElement"> 
+											<input type="text" class="inputElement "  name="{$FIELD_NAME}" data-rule-required="true" {if $FIELD_VALIDATION[$FIELD_NAME]} {$FIELD_VALIDATION[$FIELD_NAME]} {/if} value="{$FIELD_DATA[$FIELD_NAME]}" />
+											{if $FIELD_NAME == 'upload_maxsize'}
+												<div class="input-group-addon">{vtranslate('LBL_MB', $QUALIFIED_MODULE)}</div>
+											{/if}
+										</div>
+									{/if}
+								</div>
+							</div>
+						{/foreach}
+					</div>
+					<div class='modal-overlay-footer clearfix'>
+						<div class=" row clearfix">
+							<div class=' textAlignCenter col-lg-12 col-md-12 col-sm-12 '>
+								<button type='submit' class='btn btn-success saveButton'  >{vtranslate('LBL_SAVE', $MODULE)}</button>&nbsp;&nbsp;
+								<a class='cancelLink' type="reset">{vtranslate('LBL_CANCEL', $MODULE)}</a>
+							</div>
+						</div>
+					</div>
+				</form>
+			</div>
+		</div>
+	</div>
+{/strip}
 
diff --git a/layouts/v7/modules/Settings/Vtiger/OutgoingServerEdit.tpl b/layouts/v7/modules/Settings/Vtiger/OutgoingServerEdit.tpl
index e7f6a0ad8985498cc818f3df1347a1f7e6951ebe..dd97f9ec0065524ba55965f349a21f09d678222e 100644
--- a/layouts/v7/modules/Settings/Vtiger/OutgoingServerEdit.tpl
+++ b/layouts/v7/modules/Settings/Vtiger/OutgoingServerEdit.tpl
@@ -36,7 +36,7 @@
 							<tbody>
 								<tr>
 									<td class="{$WIDTHTYPE} fieldLabel"><label>{vtranslate('LBL_SERVER_TYPE', $QUALIFIED_MODULE)}</label></td>
-									<td class="fieldValue {$WIDTHTYPE}">
+									<td class="{$WIDTHTYPE} fieldValue">
 										<div class=" col-lg-6 col-md-6 col-sm-12">
 											<select class="select2 inputElement col-lg-12 col-md-12 col-lg-12" name="serverType">
 												<option value="">{vtranslate('LBL_SELECT_OPTION','Vtiger')}</option>
diff --git a/layouts/v7/modules/Vtiger/BreadCrumbs.tpl b/layouts/v7/modules/Vtiger/BreadCrumbs.tpl
index 81ddbcd6796219a87e01ecd88535c3257316fbc6..d0a860e3d2aeb50855c3d5d96e477cee467f53ed 100644
--- a/layouts/v7/modules/Vtiger/BreadCrumbs.tpl
+++ b/layouts/v7/modules/Vtiger/BreadCrumbs.tpl
@@ -1,29 +1,26 @@
-{*<!--
-/*********************************************************************************
-** The contents of this file are subject to the vtiger CRM Public License Version 1.0
- * ("License"); You may not use this file except in compliance with the License
- * The Original Code is: vtiger CRM Open Source
- * The Initial Developer of the Original Code is vtiger.
- * Portions created by vtiger are Copyright (C) vtiger.
- * All Rights Reserved.
-*
- ********************************************************************************/
- -->*}
+{*+**********************************************************************************
+* The contents of this file are subject to the vtiger CRM Public License Version 1.1
+* ("License"); You may not use this file except in compliance with the License
+* The Original Code is: vtiger CRM Open Source
+* The Initial Developer of the Original Code is vtiger.
+* Portions created by vtiger are Copyright (C) vtiger.
+* All Rights Reserved.
+*************************************************************************************}
+
 <div id="{$BREADCRUMB_ID}" class="breadcrumb">
-    <ul class="crumbs">
-        {assign var=ZINDEX value=9}
-        {foreach key=CRUMBID item=STEPTEXT from=$BREADCRUMB_LABELS name=breadcrumbLabels}
-            {assign var=INDEX value=$smarty.foreach.breadcrumbLabels.index}
-            {assign var=INDEX value=$INDEX+1}
-            <li class="step {if $smarty.foreach.breadcrumbLabels.first} first {$FIRSTBREADCRUMB} {else} {$ADDTIONALCLASS} {/if} {if $smarty.foreach.breadcrumbLabels.last} last {/if} {if $ACTIVESTEP eq $INDEX}active{/if}"
-                id="{$CRUMBID}" data-value="{$INDEX}" style="z-index:{$ZINDEX}">
-                <a href="#">
-                    <span class="stepNum">{$INDEX}</span>
-                    <span class="stepText" title="{vtranslate($STEPTEXT,$MODULE)}">{vtranslate($STEPTEXT,$MODULE)}</span>
-                </a>
-            </li>
-            
-            {assign var=ZINDEX value=$ZINDEX-1}
-        {/foreach}
-    </ul>
+	<ul class="crumbs">
+		{assign var=ZINDEX value=9}
+		{foreach key=CRUMBID item=STEPTEXT from=$BREADCRUMB_LABELS name=breadcrumbLabels}
+			{assign var=INDEX value=$smarty.foreach.breadcrumbLabels.index}
+			{assign var=INDEX value=$INDEX+1}
+			<li class="step {if $smarty.foreach.breadcrumbLabels.first} first {$FIRSTBREADCRUMB} {else} {$ADDTIONALCLASS} {/if} {if $smarty.foreach.breadcrumbLabels.last} last {/if} {if $ACTIVESTEP eq $INDEX}active{/if}"
+				id="{$CRUMBID}" data-value="{$INDEX}" style="z-index:{$ZINDEX}">
+				<a href="#">
+					<span class="stepNum">{$INDEX}</span>
+					<span class="stepText" title="{vtranslate($STEPTEXT,$MODULE)}">{vtranslate($STEPTEXT,$MODULE)}</span>
+				</a>
+			</li>
+			{assign var=ZINDEX value=$ZINDEX-1}
+		{/foreach}
+	</ul>
 </div>
\ No newline at end of file
diff --git a/layouts/v7/skins/contact/style.css b/layouts/v7/skins/contact/style.css
index e4f565feb5f5b3ee22b77e79659b4f869feb4db6..f07de9f68083287254668e905ce0bc3ecd401f5e 100644
--- a/layouts/v7/skins/contact/style.css
+++ b/layouts/v7/skins/contact/style.css
@@ -2762,6 +2762,9 @@ th {
 .active .stepNum {
   color: #FFFFFF;
 }
+.mailBoxEditDiv .crumbs li {
+  width: 22%;
+}
 .stepNum {
   display: inline-block;
   padding: 0 5px;
diff --git a/layouts/v7/skins/inventory/style.css b/layouts/v7/skins/inventory/style.css
index f8fc835882f783f829e2884084834a8b191f4bdd..f71774d5f1f44e648ea89530dfcedf1db45840bb 100644
--- a/layouts/v7/skins/inventory/style.css
+++ b/layouts/v7/skins/inventory/style.css
@@ -2762,6 +2762,9 @@ th {
 .active .stepNum {
   color: #FFFFFF;
 }
+.mailBoxEditDiv .crumbs li {
+  width: 22%;
+}
 .stepNum {
   display: inline-block;
   padding: 0 5px;
diff --git a/layouts/v7/skins/marketing/style.css b/layouts/v7/skins/marketing/style.css
index 332b24e2cb9006fd84ffd8b19f1a487efb49a435..b7723d7fd8ec0de8cd97c0864394e9d39143a5ca 100644
--- a/layouts/v7/skins/marketing/style.css
+++ b/layouts/v7/skins/marketing/style.css
@@ -2762,6 +2762,9 @@ th {
 .active .stepNum {
   color: #FFFFFF;
 }
+.mailBoxEditDiv .crumbs li {
+  width: 22%;
+}
 .stepNum {
   display: inline-block;
   padding: 0 5px;
diff --git a/layouts/v7/skins/marketing_and_sales/style.css b/layouts/v7/skins/marketing_and_sales/style.css
index fcf59fd6613f316a46e4646d4e36ff9fcbf86630..603891c836076c9e81d724042af802025d759032 100644
--- a/layouts/v7/skins/marketing_and_sales/style.css
+++ b/layouts/v7/skins/marketing_and_sales/style.css
@@ -2762,6 +2762,9 @@ th {
 .active .stepNum {
   color: #FFFFFF;
 }
+.mailBoxEditDiv .crumbs li {
+  width: 22%;
+}
 .stepNum {
   display: inline-block;
   padding: 0 5px;
diff --git a/layouts/v7/skins/project/style.css b/layouts/v7/skins/project/style.css
index 7e631f92779f51de02363b89e36c2013312df469..62c0f6482564683e903db935bb4ed93ac0a457ac 100644
--- a/layouts/v7/skins/project/style.css
+++ b/layouts/v7/skins/project/style.css
@@ -2762,6 +2762,9 @@ th {
 .active .stepNum {
   color: #FFFFFF;
 }
+.mailBoxEditDiv .crumbs li {
+  width: 22%;
+}
 .stepNum {
   display: inline-block;
   padding: 0 5px;
diff --git a/layouts/v7/skins/sales/style.css b/layouts/v7/skins/sales/style.css
index b51c53d838576274d2ead8f8681069cda0a88859..41927295896fc8a520b5dcf8017a25729d5f1527 100644
--- a/layouts/v7/skins/sales/style.css
+++ b/layouts/v7/skins/sales/style.css
@@ -2762,6 +2762,9 @@ th {
 .active .stepNum {
   color: #FFFFFF;
 }
+.mailBoxEditDiv .crumbs li {
+  width: 22%;
+}
 .stepNum {
   display: inline-block;
   padding: 0 5px;
diff --git a/layouts/v7/skins/support/style.css b/layouts/v7/skins/support/style.css
index 494bbe7e712769959f813663fd07d0b131b55571..4c7854f3c25f5e629e01ee2c06032d0af3a0a525 100644
--- a/layouts/v7/skins/support/style.css
+++ b/layouts/v7/skins/support/style.css
@@ -2762,6 +2762,9 @@ th {
 .active .stepNum {
   color: #FFFFFF;
 }
+.mailBoxEditDiv .crumbs li {
+  width: 22%;
+}
 .stepNum {
   display: inline-block;
   padding: 0 5px;
diff --git a/layouts/v7/skins/tools/style.css b/layouts/v7/skins/tools/style.css
index 1befe7e963c0ae288d6c806ea3b53f1f6e2801b9..36fd8fecb3e47e23f6312342bd0b74b827f5c6be 100644
--- a/layouts/v7/skins/tools/style.css
+++ b/layouts/v7/skins/tools/style.css
@@ -2762,6 +2762,9 @@ th {
 .active .stepNum {
   color: #FFFFFF;
 }
+.mailBoxEditDiv .crumbs li {
+  width: 22%;
+}
 .stepNum {
   display: inline-block;
   padding: 0 5px;
diff --git a/modules/Settings/MailConverter/actions/CheckMailBoxMaxLimit.php b/modules/Settings/MailConverter/actions/CheckMailBoxMaxLimit.php
index c25e61e93bb37891840e250ee066382d01c3cf91..fd544c8ef240a501076bb58e546da3760110eca8 100644
--- a/modules/Settings/MailConverter/actions/CheckMailBoxMaxLimit.php
+++ b/modules/Settings/MailConverter/actions/CheckMailBoxMaxLimit.php
@@ -14,11 +14,12 @@ class Settings_MailConverter_CheckMailBoxMaxLimit_Action extends Settings_Vtiger
 		$recordsCount = Settings_MailConverter_Record_Model::getCount();
 		$qualifiedModuleName = $request->getModule(false);
 		$response = new Vtiger_Response();
-		if ($recordsCount < 2) {
+        global $max_mailboxes;
+        if ($recordsCount < $max_mailboxes) {
 			$result = array(true);
 			$response->setResult($result);
 		} else {
-			$response->setError(vtranslate('LBL_MAX_LIMIT_ONLY_TWO', $qualifiedModuleName));
+			$response->setError(vtranslate('LBL_MAX_LIMIT_EXCEEDED', $qualifiedModuleName));
 		}
 		$response->emit();
 	}
diff --git a/modules/Settings/MailConverter/actions/DeleteMailBox.php b/modules/Settings/MailConverter/actions/DeleteMailBox.php
index 01b9fbb152b978ddb50979d3a8259e2e73ffd81f..80d8340ac1bd7484452d9d55f449259c0e192c99 100644
--- a/modules/Settings/MailConverter/actions/DeleteMailBox.php
+++ b/modules/Settings/MailConverter/actions/DeleteMailBox.php
@@ -32,8 +32,8 @@ class Settings_MailConverter_DeleteMailBox_Action extends Settings_Vtiger_Index_
 		$response->setResult($result);
 		$response->emit();
 	}
-    
-    public function validateRequest(Vtiger_Request $request) {
-        $request->validateWriteAccess();
-    }
+        
+        public function validateRequest(Vtiger_Request $request) { 
+            $request->validateWriteAccess(); 
+        }
 }
\ No newline at end of file
diff --git a/modules/Settings/MailConverter/actions/DeleteRule.php b/modules/Settings/MailConverter/actions/DeleteRule.php
index 17c8291870673fca9849e11e63f6f103798167f6..4120bde456174849f4e2f5a58b37b29c5dd51b14 100644
--- a/modules/Settings/MailConverter/actions/DeleteRule.php
+++ b/modules/Settings/MailConverter/actions/DeleteRule.php
@@ -23,12 +23,8 @@ class Settings_MailConverter_DeleteRule_Action extends Settings_Vtiger_Index_Act
 	public function process(Vtiger_Request $request) {
 		$recordId = $request->get('record');
 		$qualifiedModuleName = $request->getModule(false);
-        
-        
-        $ruleRecordModel = Vtiger_Loader::getComponentClassName('Model', 'RuleRecord', $qualifiedModuleName);
-        $ruleRecordModel = new $ruleRecordModel();
-        
-		$recordModel = call_user_func_array(array($ruleRecordModel,'getInstanceById'),array($recordId));
+
+		$recordModel = Settings_MailConverter_RuleRecord_Model::getInstanceById($recordId);
 		$scannerId = $recordModel->getScannerId();
 
 		$response = new Vtiger_Response();
@@ -40,8 +36,8 @@ class Settings_MailConverter_DeleteRule_Action extends Settings_Vtiger_Index_Act
 		}
 		$response->emit();
 	}
-    
-    public function validateRequest(Vtiger_Request $request) {
-        $request->validateWriteAccess();
-    }
+        
+        public function validateRequest(Vtiger_Request $request) { 
+            $request->validateWriteAccess(); 
+        } 
 }
\ No newline at end of file
diff --git a/modules/Settings/MailConverter/actions/SaveFolders.php b/modules/Settings/MailConverter/actions/SaveFolders.php
index e98946f26903cb61f18b0bc358ef3533643f8127..4709877860d60d74e4eff6c9ac18f50d61a688f8 100755
--- a/modules/Settings/MailConverter/actions/SaveFolders.php
+++ b/modules/Settings/MailConverter/actions/SaveFolders.php
@@ -15,9 +15,7 @@ class Settings_MailConverter_SaveFolders_Action extends Settings_Vtiger_Index_Ac
         $qualifiedModuleName = $request->getModule(false);
         $checkedFolders = $request->get('folders');
         $folders = explode(',', $checkedFolders);
-        
-        $moduleModel = Settings_Vtiger_Module_Model::getInstance($qualifiedModuleName);
-        $moduleModel->updateFolders($recordId, $folders);
+        Settings_MailConverter_Module_Model::updateFolders($recordId, $folders);
 
         $response = new Vtiger_Response();
 
@@ -26,11 +24,8 @@ class Settings_MailConverter_SaveFolders_Action extends Settings_Vtiger_Index_Ac
         $response->setResult($result);
 
         $response->emit();
-    }
-        
-    public function validateRequest(Vtiger_Request $request) {
-        $request->validateWriteAccess();
-    }
+        }
+
 }
 
 ?>
\ No newline at end of file
diff --git a/modules/Settings/MailConverter/actions/SaveMailBox.php b/modules/Settings/MailConverter/actions/SaveMailBox.php
index 6d856a7bca2bd635c40eee5ce008c53db5c6bd47..720e213bf35d47018fbcf8612d5c116e6bd8e6b7 100644
--- a/modules/Settings/MailConverter/actions/SaveMailBox.php
+++ b/modules/Settings/MailConverter/actions/SaveMailBox.php
@@ -23,9 +23,7 @@ class Settings_MailConverter_SaveMailBox_Action extends Settings_Vtiger_Index_Ac
 		$recordModel->set('scannerOldName', $request->get('scannerOldName'));
 		$fieldsList = $recordModel->getModule()->getFields();
 		foreach ($fieldsList as $fieldName=>$fieldModel) {
-			$fieldValue = $request->get($fieldName);
-			if(!empty($fieldValue) || $fieldName == 'isvalid')
-				$recordModel->set($fieldName, $request->get($fieldName));
+			$recordModel->set($fieldName, $request->get($fieldName));
 		}
 
 		$status = $recordModel->save();
@@ -37,18 +35,12 @@ class Settings_MailConverter_SaveMailBox_Action extends Settings_Vtiger_Index_Ac
 			$result['listViewUrl'] = $recordModel->getListUrl();
 			$response->setResult($result);
 		} else {
-            $errorMsg = $recordModel->get('errorMsg');
-            if(!empty($errorMsg)) {
-                $response->setError(vtranslate($errorMsg, $qualifiedModuleName));
-            } else {
-                $response->setError(vtranslate('LBL_CONNECTION_TO_MAILBOX_FAILED', $qualifiedModuleName));
-            }
+			$response->setError(vtranslate('LBL_CONNECTION_TO_MAILBOX_FAILED', $qualifiedModuleName));
 		}
 		$response->emit();
 	}
-    
-    public function validateRequest(Vtiger_Request $request) {
-        $request->validateWriteAccess();
-    }
-
+        
+        public function validateRequest(Vtiger_Request $request) { 
+            $request->validateWriteAccess(); 
+        }
 }
\ No newline at end of file
diff --git a/modules/Settings/MailConverter/actions/SaveRule.php b/modules/Settings/MailConverter/actions/SaveRule.php
index 51732071e36264deb4fe392270c6237c874ca7f2..122fdacb213ca4ecc0b54c7fd331ecc99a293ea7 100644
--- a/modules/Settings/MailConverter/actions/SaveRule.php
+++ b/modules/Settings/MailConverter/actions/SaveRule.php
@@ -26,65 +26,30 @@ class Settings_MailConverter_SaveRule_Action extends Settings_Vtiger_Index_Actio
 		$action = $request->get('action1');
 		$request->set('action', $action);
 		$qualifiedModuleName = $request->getModule(false);
-        $modelClassName = Vtiger_Loader::getComponentClassName('Model','RuleRecord', $qualifiedModuleName);
+
 		if ($recordId) {
-            $recordModel = call_user_func_array(array($modelClassName,'getInstanceById'), array($recordId));
+			$recordModel = Settings_MailConverter_RuleRecord_Model::getInstanceById($recordId);
 		} else {
-            $recordModel = call_user_func_array(array($modelClassName,'getCleanInstance'), array($scannerId));
+			$recordModel = Settings_MailConverter_RuleRecord_Model::getCleanInstance($scannerId);
 		}
+
+		$recordModel->assignedTo = $request->get('assignedTo');
+		$recordModel->cc = $request->get('cc');
+		$recordModel->bcc = $request->get('bcc');
 		$fieldsList = $recordModel->getFields();
 		foreach ($fieldsList as $fieldName) {
 			$recordModel->set($fieldName, $request->get($fieldName));
 		}
 		$recordModel->set('newAction', $request->get('action'));
-        
-        $ruleId = $recordModel->save();
-        
-        $status = $this->saveBodyRule($ruleId, $request);
-        $response = new Vtiger_Response();
-        if($status) {
-            $response->setResult(array('message' => vtranslate('LBL_SAVED_SUCCESSFULLY', $qualifiedModuleName), 'id' => $ruleId, 'scannerId' => $scannerId));
-        } else {
-            $response->setError(vtranslate('LBL_MULTIPLE_FIELDS_MAPPED', $qualifiedModuleName));
-        }
+
+		$ruleId = $recordModel->save();
+
+		$response = new Vtiger_Response();
+		$response->setResult(array('message' => vtranslate('LBL_SAVED_SUCCESSFULLY', $qualifiedModuleName), 'id' => $ruleId, 'scannerId' => $scannerId));
 		$response->emit();
 	}
-
-    public function saveBodyRule($ruleId, $request) {
-        $mailBody = $request->get('mailBody');
-        $scannerId = $request->get('scannerId');
-        $qualifiedModule = $request->getModule(false);
-        $bodyRuleModel = Settings_MailConverter_BodyRule_Model::getCleanInstance($qualifiedModule);
-        
-        if(empty($mailBody)) {
-            $bodyRuleModel->deleteBodyRule($scannerId, $ruleId);
-            return true;
-        }
-        $delimiter = $request->get('delimeter');
-        $mappingData = $request->get('mappingData');
-        $action = $request->get('action');
-        
-        foreach($mappingData as $key => $value) {
-            if($value != ' ') {
-                $mapFields[$key] = $value;
-            }
-        }
         
-        if(count($mapFields) == count(array_unique($mapFields))) {
-            $bodyRuleModel->set('scannerId', $scannerId);
-            $bodyRuleModel->set('ruleId', $ruleId);
-            $bodyRuleModel->set('delimiter', $delimiter);
-            $bodyRuleModel->set('filedsMapping', $mapFields);
-            $bodyRuleModel->set('action', $action);
-            $bodyRuleModel->set('body', $mailBody);
-            $bodyRuleModel->saveBodyRule();
-            return true;
-        } else {
-            return false;
+        public function validateRequest(Vtiger_Request $request) { 
+            $request->validateWriteAccess(); 
         }
-    }
-    
-    public function validateRequest(Vtiger_Request $request) {
-        $request->validateWriteAccess();
-    }
 }
\ No newline at end of file
diff --git a/modules/Settings/MailConverter/actions/ScanNow.php b/modules/Settings/MailConverter/actions/ScanNow.php
index b000389049fb62e2168abb081584aeb06667de52..a61fe2ddfc04f5fc7da0a07e3539befdc6cd4f26 100644
--- a/modules/Settings/MailConverter/actions/ScanNow.php
+++ b/modules/Settings/MailConverter/actions/ScanNow.php
@@ -29,20 +29,12 @@ class Settings_MailConverter_ScanNow_Action extends Settings_Vtiger_Index_Action
 		$response = new Vtiger_Response();
 		if (is_bool($status) && $status) {
 			$result = array('message'=> vtranslate('LBL_SCANNED_SUCCESSFULLY', $qualifiedModuleName));
-            $recordModel = Settings_MailConverter_Record_Model::getInstanceById($recordId);
             $result['id'] = $recordModel->getId();
-            $lastScanTime = $recordModel->getLastScanTime();
-            $moduleModel = Settings_Vtiger_Module_Model::getInstance($qualifiedModuleName);
-            $foldersScanned = $moduleModel->getScannedFolders($recordId);
-            $scanTimeMsg = vtranslate('LBL_LAST_SCAN_AT', $qualifiedModuleName).$lastScanTime.'<br>'.
-                    vtranslate('LBL_FOLDERS_SCANNED', $qualifiedModuleName).' : <strong>'.implode(', ', $foldersScanned).'</strong>';
-            $result['lastScanMessage'] = $scanTimeMsg;
 			$response->setResult($result);
 		} else if($status) {
-            $response->setError($status);
-        } else {
-            $errorMsg = $recordModel->get('errorMsg');
-            $response->setError(vtranslate($errorMsg, $qualifiedModuleName));
+                        $response->setError($status);
+                } else {
+			$response->setError(vtranslate($request->getModule(), $qualifiedModuleName). ' ' .vtranslate('LBL_IS_IN_RUNNING_STATE', $qualifiedModuleName));
 		}
 		$response->emit();
 	}
diff --git a/modules/Settings/MailConverter/actions/UpdateSequence.php b/modules/Settings/MailConverter/actions/UpdateSequence.php
index f491f21cfedfb015c604ef3ded2adb3cfbd7fed9..4d9ede19f2d884ff3f494390b6293ccc862f3f80 100644
--- a/modules/Settings/MailConverter/actions/UpdateSequence.php
+++ b/modules/Settings/MailConverter/actions/UpdateSequence.php
@@ -36,8 +36,8 @@ class Settings_MailConverter_UpdateSequence_Action extends Settings_Vtiger_Index
 
 		$response->emit();
 	}
-    
-    public function validateRequest(Vtiger_Request $request) {
-        $request->validateWriteAccess();
-    }
+        
+        public function validateRequest(Vtiger_Request $request) { 
+            $request->validateWriteAccess(); 
+        } 
 }
\ No newline at end of file
diff --git a/modules/Settings/MailConverter/handlers/MailBox.php b/modules/Settings/MailConverter/handlers/MailBox.php
index ee9c3cc0026056a57c552922c6d713e0a23da9fa..2d209c87407fdd155e9d7766f381c671a5f59a95 100644
--- a/modules/Settings/MailConverter/handlers/MailBox.php
+++ b/modules/Settings/MailConverter/handlers/MailBox.php
@@ -29,8 +29,6 @@ class Vtiger_MailBox {
 
 	// Mailbox crendential information (as a map)
 	var $_mailboxsettings = false;
-    // IMAP Errors
-    var $_imaperror = false;
 
 	/** DEBUG functionality. */
 	var $debug = false;
@@ -117,7 +115,7 @@ class Vtiger_MailBox {
 		$this->_imap = $imap;
 		return $isconnected;
 	}
-    
+
 	/**
 	 * Open the mailbox folder.
 	 * @param $folder Folder name to open
@@ -134,9 +132,8 @@ class Vtiger_MailBox {
 
 		$isconnected = false;
 		$connectString = $this->_imapurl;
-        $folderUrl = MailManager_Connector_Connector::convertCharacterEncoding(html_entity_decode("$connectString$folder"),'UTF7-IMAP','UTF-8');
-		$this->log("Trying to open folder using $folderUrl");
-		$imap = @imap_open($folderUrl, $mailboxsettings[username], $mailboxsettings[password]);
+		$this->log("Trying to open folder using $connectString$folder");
+		$imap = @imap_open("$connectString$folder", $mailboxsettings[username], $mailboxsettings[password]);
 		if($imap) {
 
 			// Perform cleanup task before re-initializing the connection
@@ -156,7 +153,6 @@ class Vtiger_MailBox {
 	 * @return imap_search records or false
 	 */
 	function search($folder, $searchQuery=false) {
-        $folder = decode_html($folder);
 		if(!$searchQuery) {
 			$lastscanOn = $this->_scannerinfo->getLastscan($folder);
 			$searchfor = $this->_scannerinfo->searchfor;
@@ -187,8 +183,7 @@ class Vtiger_MailBox {
 			$imapfolders = imap_list($this->_imap, $this->_imapurl, '*');
 			if($imapfolders) {
 				foreach($imapfolders as $imapfolder) {
-					$folder = substr($imapfolder, strlen($this->_imapurl));
-                    $folders[] = MailManager_Connector_Connector::convertCharacterEncoding($folder, 'UTF-8', 'UTF7-IMAP');
+					$folders[] = substr($imapfolder, strlen($this->_imapurl));
 				}
 			} else {
                             return imap_last_error();
@@ -215,6 +210,8 @@ class Vtiger_MailBox {
 		    if (strtoupper($markas) == 'SEEN') {
 				$markas = "\\Seen";
 				imap_setflag_full($this->_imap, $messageid, $markas);
+		    } else if (strtoupper($markas) == 'UNSEEN') {
+				imap_clearflag_full($this->_imap, $messageid, "\\Seen");
 		    }
 		}
 	}
diff --git a/modules/Settings/MailConverter/handlers/MailRecord.php b/modules/Settings/MailConverter/handlers/MailRecord.php
index 7d7cffe8d3de1614dc97332d606ef84da5fb0959..5defb56f73eb42940547cd46745da2e083e1c57e 100644
--- a/modules/Settings/MailConverter/handlers/MailRecord.php
+++ b/modules/Settings/MailConverter/handlers/MailRecord.php
@@ -9,7 +9,6 @@
  *
  ********************************************************************************/
 
-require_once 'modules/Settings/MailConverter/handlers/MailParser.php';
 /**
  * This class provides structured way of accessing details of email.
  */
@@ -30,9 +29,9 @@ class Vtiger_MailRecord {
 	var $_subject;
 	// BODY (either HTML / PLAIN message)
 	var $_body;
-    // Name of Mail Sender 
+     // Name of Mail Sender 
     var $_fromname;
-	// CHARSET of the body content
+    // CHARSET of the body content
 	var $_charset;
 	// If HTML message was set as body content
 	var $_isbodyhtml;
@@ -51,13 +50,10 @@ class Vtiger_MailRecord {
 	/** DEBUG Functionality. */
 	var $debug = false;
 	function log($message=false) {
-		if(!$message)
-            $message = $this->__toString();
+		if(!$message) $message = $this->__toString();
 
 		global $log;
-		if($log && $this->debug) {
-            $log->debug($message);
-        }
+		if($log && $this->debug) { $log->debug($message); }
 		else if($this->debug) {
 			echo var_export($message, true) . "\n";
 		}
@@ -83,10 +79,8 @@ class Vtiger_MailRecord {
 	 * Constructor.
 	 */
 	function __construct($imap, $messageid, $fetchbody=true) {
-        if($imap) {
-            $this->__parseHeader($imap, $messageid);
-            if($fetchbody) $this->__parseBody($imap, $messageid);
-        }
+		$this->__parseHeader($imap, $messageid);
+		if($fetchbody) $this->__parseBody($imap, $messageid);
 	}
 
 	/**
@@ -147,19 +141,13 @@ class Vtiger_MailRecord {
 		if ($mb_function === NULL) $mb_function = function_exists('mb_convert_encoding');
 		if ($iconv_function === NULL) $iconv_function = function_exists('iconv');
 
-		$mbAcceptedEncodings=array();
-		$mbAcceptedEncodings=  mb_list_encodings();
-		if(!in_array($from,$mbAcceptedEncodings)){
-		   return iconv($from,"UTF-8", $input);
-		} else {
-			if($mb_function) {
-				if(!$from) $from = mb_detect_encoding($input);
+		if($mb_function) {
+			if(!$from) $from = mb_detect_encoding($input);
 
-				if(strtolower(trim($to)) == strtolower(trim($from))) {                         
+			if(strtolower(trim($to)) == strtolower(trim($from))) {                         
 					return $input;
-				} else {
-					return mb_convert_encoding($input, $to, $from);
-				}
+			} else {
+				return mb_convert_encoding($input, $to, $from);
 			}
 		}
 		return $input;
@@ -172,15 +160,14 @@ class Vtiger_MailRecord {
 		if(is_null($words)) $words = array();
 		$returnvalue = $input;
 		
-		preg_match_all('/=\?([^\?]+)\?([^\?]+)\?([^\?]+)\?=/', $input, $matches); 
-		array_filter($matches); 
-		if(count($matches[0]) > 0) { 
-			$decodedArray =  imap_mime_header_decode($input); 
-			foreach($decodedArray as $part=>$prop) {
-				$decodevalue = $prop->text; 
-				$charset = $prop->charset;
-				if($charset != 'default')
-					$value = self::__convert_encoding($decodevalue, $targetEncoding, $charset);	
+		preg_match_all('/=\?([^\?]+)\?([^\?]+)\?([^\?]+)\?=/', $input, $matches);
+                array_filter($matches);
+                if(count($matches[0])>0){
+                $decodedArray=  imap_mime_header_decode($input);
+                foreach($decodedArray as $part=>$prop){
+                            $decodevalue=$prop->text;
+                            $charset=$prop->charset;
+				$value = self::__convert_encoding($decodevalue, $targetEncoding, $charset);				
 				array_push($words, $value);				
 			}
 		}
@@ -229,7 +216,7 @@ class Vtiger_MailRecord {
 		$this->_uniqueid = $mailheader->message_id;
 
 		$this->_from = $this->__getEmailIdList($mailheader->from);
-        $this->_fromname = self::__mime_decode($mailheader->from[0]->personal);
+                $this->_fromname = self::__mime_decode($mailheader->from[0]->personal);
 		$this->_to   = $this->__getEmailIdList($mailheader->to);
 		$this->_cc   = $this->__getEmailIdList($mailheader->cc);
 		$this->_bcc  = $this->__getEmailIdList($mailheader->bcc);
@@ -239,11 +226,10 @@ class Vtiger_MailRecord {
 		$this->_subject = self::__mime_decode($mailheader->subject);
 		if(!$this->_subject) $this->_subject = 'Untitled';
 	}
-    
 	// Modified: http://in2.php.net/manual/en/function.imap-fetchstructure.php#85685
 	function __parseBody($imap, $messageid) {
 		$structure = imap_fetchstructure($imap, $messageid);
-		
+
 		$this->_plainmessage = '';
 		$this->_htmlmessage = '';
 		$this->_body = '';
@@ -283,15 +269,14 @@ class Vtiger_MailRecord {
 
 		$this->_bodyparsed = true;
 	}
-    
 	// Modified: http://in2.php.net/manual/en/function.imap-fetchstructure.php#85685	
 	function __getpart($imap, $messageid, $p, $partno) {
 	    // $partno = '1', '2', '2.1', '2.1.3', etc if multipart, 0 if not multipart
     	
 	    // DECODE DATA
     	$data = ($partno)? 
-			imap_fetchbody($imap,$messageid,$partno, FT_PEEK):  // multipart
-			imap_body($imap,$messageid, FT_PEEK);				// not multipart
+			imap_fetchbody($imap,$messageid,$partno):  // multipart
+			imap_body($imap,$messageid);               // not multipart
 	
 		// Any part may be encoded, even plain text messages, so check everything.
     	if ($p->encoding==4) $data = quoted_printable_decode($data);
@@ -307,7 +292,7 @@ class Vtiger_MailRecord {
 	    if ($p->dparameters) {
 			foreach ($p->dparameters as $x) $params[ strtolower( $x->attribute ) ] = $x->value;
 		}
-		
+
 	    // ATTACHMENT
     	// Any part with a filename is an attachment,
 	    // so an attached text file (type 0) is not mistaken as the message.
@@ -345,14 +330,5 @@ class Vtiger_MailRecord {
             	$this->__getpart($imap,$messageid,$p2,$partno.'.'.($partno0+1));  // 1.2, 1.2.1, etc.
     	}
 	}
-        
-        function getParsedBody() {
-            if($this->_isbodyhtml) {
-                $htmlParser = new Vtiger_MailParser($this->getBodyHTML());
-                return $htmlParser->parseHtml();
-            } else {
-                return $this->getBodyText();
-            }
-        }
 }
 ?>
diff --git a/modules/Settings/MailConverter/handlers/MailScanner.php b/modules/Settings/MailConverter/handlers/MailScanner.php
index a21408652e7a7ab4452db8d057e276afab33e274..93d56a41e70008d01c22b8388aff18db73376be1 100644
--- a/modules/Settings/MailConverter/handlers/MailScanner.php
+++ b/modules/Settings/MailConverter/handlers/MailScanner.php
@@ -138,7 +138,6 @@ class Vtiger_MailScanner {
 			$rescanFolderFlag = false;
 			$this->updateLastScan($lookAtFolder, $rescanFolderFlag);
 		}
-        $this->updateScannerLastScanTime();
 		// Close the mailbox at end
 		$mailbox->close();
                 return true;
@@ -179,7 +178,7 @@ class Vtiger_MailScanner {
 		global $adb;
 		if($crmid === false) $crmid = null;
 		// TODO Make sure we have unique entry
-		$adb->pquery("INSERT INTO vtiger_message_ids(scannerid, messageid, crmid) VALUES(?,?,?)",
+		$adb->pquery("INSERT INTO vtiger_mailscanner_ids(scannerid, messageid, crmid) VALUES(?,?,?)",
 			Array($this->_scannerinfo->scannerid, $mailrecord->_uniqueid, $crmid));
 	}
 
@@ -188,8 +187,8 @@ class Vtiger_MailScanner {
 	 */
 	function isMessageScanned($mailrecord, $lookAtFolder) {
 		global $adb;
-		$messages = $adb->pquery("SELECT 1 FROM vtiger_message_ids WHERE messageid=?",
-			Array($mailrecord->_uniqueid));
+		$messages = $adb->pquery("SELECT 1 FROM vtiger_mailscanner_ids WHERE scannerid=? AND messageid=?",
+			Array($this->_scannerinfo->scannerid, $mailrecord->_uniqueid));
 
 		$folderRescan = $this->_scannerinfo->needRescan($lookAtFolder);
 		$isScanned = false;
@@ -201,7 +200,7 @@ class Vtiger_MailScanner {
 			$relatedCRMId = $adb->query_result($messages, 0, 'crmid');
 
 			if($folderRescan && empty($relatedCRMId)) {
-				$adb->pquery("DELETE FROM vtiger_message_ids WHERE scannerid=? AND messageid=?",
+				$adb->pquery("DELETE FROM vtiger_mailscanner_ids WHERE scannerid=? AND messageid=?",
 					Array($this->_scannerinfo->scannerid, $mailrecord->_uniqueid));
 				$isScanned = false;
 			}
@@ -235,14 +234,10 @@ class Vtiger_MailScanner {
 	var $_cachedLeadIds = Array();
 	var $_cachedAccountIds = Array();
 	var $_cachedTicketIds = Array();
-    var $_cachedPotentialIds = Array();
-    var $_cachedHelpDeskIds = Array();
 	var $_cachedAccounts = Array();
 	var $_cachedContacts = Array();
 	var $_cachedLeads = Array();
 	var $_cachedTickets = Array();
-    var $_cachedPotentials = Array();
-    var $_cachedHelpdesk = Array();
 
 	/**
 	 * Lookup Contact record based on the email given.
@@ -254,13 +249,12 @@ class Vtiger_MailScanner {
 			return $this->_cachedContactIds[$email];
 		}
 		$contactid = false;
-		$lookupQuery = $this->getLookupQuery('Contacts', $email);
-                if(!$lookupQuery) {
-                    return false;
-                }
-                $contactres = $adb->pquery($lookupQuery['query'], $lookupQuery['params']);
+		$contactres = $adb->pquery("SELECT contactid FROM vtiger_contactdetails INNER JOIN vtiger_crmentity ON crmid = contactid WHERE setype = ? AND email = ? AND deleted = ?", array('Contacts', $email, 0));
 		if($adb->num_rows($contactres)) {
-                    $contactid = $adb->query_result($contactres, 0, 'contactid');
+			$deleted = $adb->query_result($contactres, 0, 'deleted');
+			if ($deleted != 1) {
+				$contactid = $adb->query_result($contactres, 0, 'contactid');
+			}
 		}
 		if($contactid) {
 			$this->log("Caching Contact Id found for email: $email");
@@ -281,13 +275,12 @@ class Vtiger_MailScanner {
 			return $this->_cachedLeadIds[$email];
 		}
 		$leadid = false;
-                $lookupQuery = $this->getLookupQuery('Leads', $email);
-                if(!$lookupQuery) {
-                    return false;
-                }
-                $leadres = $adb->pquery($lookupQuery['query'], $lookupQuery['params']);
+		$leadres = $adb->pquery("SELECT leadid FROM vtiger_leaddetails INNER JOIN vtiger_crmentity ON crmid = leadid WHERE setype=? AND email = ? AND converted = ? AND deleted = ?", array('Leads', $email, 0, 0));
 		if ($adb->num_rows($leadres)) {
-                    $leadid = $adb->query_result($leadres, 0, 'leadid');
+			$deleted = $adb->query_result($leadres, 0, 'deleted');
+			if ($deleted != 1) {
+				$leadid = $adb->query_result($leadres, 0, 'leadid');
+			}
 		}
 		if ($leadid) {
 			$this->log("Caching Lead Id found for email: $email");
@@ -309,13 +302,12 @@ class Vtiger_MailScanner {
 		}
 
 		$accountid = false;
-                $lookupQuery = $this->getLookupQuery('Accounts', $email);
-                if(!$lookupQuery) {
-                    return false;
-                }
-                $accountres = $adb->pquery($lookupQuery['query'], $lookupQuery['params']);
+		$accountres = $adb->pquery("SELECT accountid FROM vtiger_account INNER JOIN vtiger_crmentity ON crmid = accountid WHERE setype=? AND (email1 = ? OR email2 = ?) AND deleted = ?", Array('Accounts', $email, $email, 0));
 		if($adb->num_rows($accountres)) {
-                    $accountid = $adb->query_result($accountres, 0, 'accountid');
+			$deleted = $adb->query_result($accountres, 0, 'deleted');
+			if ($deleted != 1) {
+				$accountid = $adb->query_result($accountres, 0, 'accountid');
+			}
 		}
 		if($accountid) {
 			$this->log("Caching Account Id found for email: $email");
@@ -325,64 +317,8 @@ class Vtiger_MailScanner {
 		}
 		return $accountid;
 	}
-    
-    /**
-     * Lookup Potential record based on email
-     */
-    function LookupPotential($email) {
-        global $adb;
-		if($this->_cachedPotentialIds[$email]) {
-			$this->log("Reusing Cached Potential Id for email: $email");
-			return $this->_cachedPotentialIds[$email];
-		}
-
-		$potentialId = false;
-                $lookupQuery = $this->getLookupQuery('Potentials', $email);
-                if(!$lookupQuery) {
-                    return false;
-                }
-                $potentialres = $adb->pquery($lookupQuery['query'], $lookupQuery['params']);
-		if($adb->num_rows($potentialres)) {
-                    $potentialId = $adb->query_result($potentialres, 0, 'potentialid');
-		}
-		if($potentialId) {
-			$this->log("Caching Potential Id found for email: $email");
-			$this->_cachedPotentialIds[$email] = $potentialId;
-		} else {
-			$this->log("No matching Potentials found for email: $email");
-		}
-		return $potentialId;
-    }
-    
-    /**
-     * Lookup Tickets record based on email
-     */
-    function LookupHelpDesk($email) {
-        global $adb;
-		if($this->_cachedHelpDeskIds[$email]) {
-			$this->log("Reusing Cached HelpDesk Id for email: $email");
-			return $this->_cachedHelpDeskIds[$email];
-		}
-
-		$ticketId = false;
-                $lookupQuery = $this->getLookupQuery('HelpDesk', $email);
-                if(!$lookupQuery) {
-                    return false;
-                }
-                $ticketres = $adb->pquery($lookupQuery['query'], $lookupQuery['params']);
-		if($adb->num_rows($ticketres)) {
-                    $ticketId = $adb->query_result($ticketres, 0, 'ticketid');
-		}
-		if($ticketId) {
-			$this->log("Caching Ticket Id found for email: $email");
-			$this->_cachedHelpDeskIds[$email] = $ticketId;
-		} else {
-			$this->log("No matching Tickets found for email: $email");
-		}
-		return $ticketId;
-    }
 
-    /**
+	/**
 	 * Lookup Ticket record based on the subject or id given.
 	 */
 	function LookupTicket($subjectOrId) {
@@ -437,7 +373,7 @@ class Vtiger_MailScanner {
 				$account_focus = $this->_cachedAccounts[$accountid];
 				$this->log("Reusing Cached Account [" . $account_focus->column_fields[accountname] . "]");
 			} else {
-				$account_focus = CRMEntity::getInstance("Accounts");
+				$account_focus = new Accounts();
 				$account_focus->retrieve_entity_info($accountid, 'Accounts');
 				$account_focus->id = $accountid;
 
@@ -462,7 +398,7 @@ class Vtiger_MailScanner {
 				$this->log("Reusing Cached Contact [" . $contact_focus->column_fields[lastname] .
 				   	'-' . $contact_focus->column_fields[firstname] . "]");
 			} else {
-				$contact_focus = CRMEntity::getInstance("Contacts");
+				$contact_focus = new Contacts();
 				$contact_focus->retrieve_entity_info($contactid, 'Contacts');
 				$contact_focus->id = $contactid;
 
@@ -487,7 +423,7 @@ class Vtiger_MailScanner {
 				$this->log("Reusing Cached Lead [" . $lead_focus->column_fields[lastname] .
 						'-' . $lead_focus->column_fields[firstname] . "]");
 			} else {
-				$lead_focus = CRMEntity::getInstance("Leads");
+				$lead_focus = new Leads();
 				$lead_focus->retrieve_entity_info($leadid, 'Leads');
 				$lead_focus->id = $leadid;
 
@@ -498,55 +434,15 @@ class Vtiger_MailScanner {
 		}
 		return $lead_focus;
 	}
-    
-    /**
-     * Get Potential record based on email
-     */
-    function GetPotentialRecord($email) {
-        require_once('modules/Potentials/Potentials.php');
-		$potentialId = $this->LookupPotential($email);
-		$focus = false;
-		if ($potentialId) {
-			if ($this->_cachedPotentials[$potentialId]) {
-				$focus = $this->_cachedPotentials[$potentialId];
-			} else {
-				$focus = CRMEntity::getInstance("Potentials");
-				$focus->retrieve_entity_info($potentialId, 'Potentials');
-				$focus->id = $potentialId;
-				$this->_cachedPotentials[$potentialId] = $focus;
-			}
-		}
-		return $focus;
-    }
-    
-    /**
-     * Get Ticket record based on email
-     */
-    function GetTicketFocus($email) {
-        require_once('modules/HelpDesk/HelpDesk.php');
-		$ticketId = $this->LookupHelpDesk($email);
-		$focus = false;
-		if ($ticketId) {
-			if ($this->_cachedHelpdesk[$ticketId]) {
-				$focus = $this->_cachedHelpdesk[$ticketId];
-			} else {
-				$focus = CRMEntity::getInstance("HelpDesk");
-				$focus->retrieve_entity_info($ticketId, 'HelpDesk');
-				$focus->id = $ticketId;
-				$this->_cachedHelpdesk[$ticketId] = $focus;
-			}
-		}
-		return $focus;
-    }
 
-    /**
+	/**
 	 * Lookup Contact or Account based on from email and with respect to given CRMID
 	 */
 	function LookupContactOrAccount($fromemail, $checkWith) {
 		$recordid = $this->LookupContact($fromemail);
-		if ($recordid != $checkWith['contact_id'] || !$recordid) {
+		if ($checkWith['contact_id'] && $recordid != $checkWith['contact_id']) {
 			$recordid = $this->LookupAccount($fromemail);
-			if ($recordid != $checkWith['parent_id'] || !$recordid)
+			if (($checkWith['parent_id'] && $recordid != $checkWith['parent_id']))
 				$recordid = false;
 		}
 		return $recordid;
@@ -562,13 +458,21 @@ class Vtiger_MailScanner {
 		if($ticketid) {
 			if($this->_cachedTickets[$ticketid]) {
 				$ticket_focus = $this->_cachedTickets[$ticketid];
+				// Check the parentid association if specified.
+				if ($fromemail && !$this->LookupContactOrAccount($fromemail, $ticket_focus->column_fields)) {
+					$ticket_focus = false;
+				}
 				if($ticket_focus) {
 					$this->log("Reusing Cached Ticket [" . $ticket_focus->column_fields[ticket_title] ."]");
 				}
 			} else {
-				$ticket_focus = CRMEntity::getInstance("HelpDesk");
+				$ticket_focus = new HelpDesk();
 				$ticket_focus->retrieve_entity_info($ticketid, 'HelpDesk');
 				$ticket_focus->id = $ticketid;
+				// Check the parentid association if specified.
+				if ($fromemail && !$this->LookupContactOrAccount($fromemail, $ticket_focus->column_fields)) {
+					$ticket_focus = false;
+				}
 				if($ticket_focus) {
 					$this->log("Caching Ticket [" . $ticket_focus->column_fields[ticket_title] . "]");
 					$this->_cachedTickets[$ticketid] = $ticket_focus;
@@ -591,53 +495,6 @@ class Vtiger_MailScanner {
 		$adb->pquery("UPDATE vtiger_mailscanner SET isvalid=? WHERE scannerid=?", array(0,$scannerId));
     }
     
-    function updateScannerLastScanTime() {
-        $scannerId = $this->_scannerinfo->scannerid;
-        $db = PearDatabase::getInstance();
-        $db->pquery("UPDATE vtiger_mailscanner SET last_scan = ? WHERE scannerid = ?", array(date('Y-m-d H:i:s'), $scannerId));
-    }
-    
-    function getLookupQuery($module, $email) {
-        $moduleModel = Vtiger_Module_Model::getInstance($module);
-        $baseTable  = $moduleModel->get('basetable');
-        $baseTableId = $moduleModel->get('basetableid');
-        if($module == "HelpDesk") {
-            $customTable = "vtiger_ticketcf";
-        } else {
-            $customTable = "vtiger_".strtolower($module)."cf";
-        }
-        
-        $emailFields = $moduleModel->getFieldsByType('email');
-        $fieldInfos = array();
-        foreach($emailFields as $fieldName => $fieldInstance) {
-            $fieldInfos[] = array('fieldname' => $fieldName, 'columnname' => $fieldInstance->get('column'), 'tablename' => $fieldInstance->get('table'));
-        }
-        
-        if(count($fieldInfos) <= 0) {
-            return false;
-        }
-        
-        $query = "SELECT $baseTable.$baseTableId FROM $baseTable INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = $baseTable.$baseTableId";
-        $query .= " INNER JOIN $customTable ON $customTable.$baseTableId = $baseTable.$baseTableId WHERE vtiger_crmentity.setype = ? AND vtiger_crmentity.deleted = ? AND ";
-        $params = array($module, 0);
-        
-        if($module == 'Leads') {
-            $query .= "$baseTable.converted = ? AND ";
-            array_push($params, 0);
-        }
-        
-        $query .= '(';
-        foreach($fieldInfos as $key => $fieldInfo) {
-            $query .= $fieldInfo['tablename'].".".$fieldInfo['columnname']." = ? ";
-            array_push($params, $email);
-            if((count($fieldInfos) - 1) != $key) {
-                $query .= "OR ";
-            }
-        }
-        $query .= ')';
-        
-        return array('query' => $query, 'params' => $params);
-    }
 }
 
 ?>
diff --git a/modules/Settings/MailConverter/handlers/MailScannerAction.php b/modules/Settings/MailConverter/handlers/MailScannerAction.php
index 52c9cd514635da57072ade917dd7a62fd378a8fc..459ff9b33bbcf3ce721eb25f7d9ee6c90e247c26 100644
--- a/modules/Settings/MailConverter/handlers/MailScannerAction.php
+++ b/modules/Settings/MailConverter/handlers/MailScannerAction.php
@@ -9,8 +9,14 @@
  *
  ********************************************************************************/
 
+require_once('modules/Emails/Emails.php');
+require_once('modules/HelpDesk/HelpDesk.php');
+require_once('modules/ModComments/ModComments.php');
 require_once('modules/Users/Users.php');
-require_once ('modules/Settings/MailConverter/handlers/MailScannerBodyRule.php');
+require_once('modules/Documents/Documents.php');
+require_once ('modules/Leads/Leads.php');
+require_once ('modules/Contacts/Contacts.php');
+require_once ('modules/Accounts/Accounts.php');
 
 /**
  * Mail Scanner Action
@@ -25,7 +31,7 @@ class Vtiger_MailScannerAction {
 	// text representation of action
 	var $actiontext= false;
 	// target module for action
-	var $actionModule    = false;
+	var $module    = false;
 	// lookup information while taking action
 	var $lookup    = false;
 
@@ -36,11 +42,8 @@ class Vtiger_MailScannerAction {
 	var $debug     = false;
 	function log($message) {
 		global $log;
-		if($log && $this->debug) {
-			$log->debug($message);
-		}
-		else if($this->debug)
-			echo "$message\n";
+		if($log && $this->debug) { $log->debug($message); }
+		else if($this->debug) echo "$message\n";
 	}
 
 	/**
@@ -61,9 +64,9 @@ class Vtiger_MailScannerAction {
 			$this->actionid   = $adb->query_result($result, 0, 'actionid');
 			$this->scannerid  = $adb->query_result($result, 0, 'scannerid');
 			$this->actiontype = $adb->query_result($result, 0, 'actiontype');
-			$this->actionModule     = $adb->query_result($result, 0, 'module');
+			$this->module     = $adb->query_result($result, 0, 'module');
 			$this->lookup     = $adb->query_result($result, 0, 'lookup');
-			$this->actiontext = "$this->actiontype,$this->actionModule,$this->lookup";
+			$this->actiontext = "$this->actiontype,$this->module,$this->lookup";
 		}
 	}
 
@@ -75,18 +78,18 @@ class Vtiger_MailScannerAction {
 
 		$inputparts = explode(',', $actiontext);
 		$this->actiontype = $inputparts[0]; // LINK, CREATE
-		$this->actionModule     = $inputparts[1]; // Module name
+		$this->module     = $inputparts[1]; // Module name
 		$this->lookup     = $inputparts[2]; // FROM, TO
 
 		$this->actiontext = $actiontext;
 
 		if($this->actionid) {
 			$adb->pquery("UPDATE vtiger_mailscanner_actions SET scannerid=?, actiontype=?, module=?, lookup=? WHERE actionid=?",
-				Array($this->scannerid, $this->actiontype, $this->actionModule, $this->lookup, $this->actionid));
+				Array($this->scannerid, $this->actiontype, $this->module, $this->lookup, $this->actionid));
 		} else {
 			$this->sequence = $this->__nextsequence();
 			$adb->pquery("INSERT INTO vtiger_mailscanner_actions(scannerid, actiontype, module, lookup, sequence) VALUES(?,?,?,?,?)",
-				Array($this->scannerid, $this->actiontype, $this->actionModule, $this->lookup, $this->sequence));
+				Array($this->scannerid, $this->actiontype, $this->module, $this->lookup, $this->sequence));
 			$this->actionid = $adb->database->Insert_ID();
 		}
 		$checkmapping = $adb->pquery("SELECT COUNT(*) AS ruleaction_count FROM vtiger_mailscanner_ruleactions
@@ -128,59 +131,29 @@ class Vtiger_MailScannerAction {
 	function apply($mailscanner, $mailrecord, $mailscannerrule, $matchresult) {
 		$returnid = false;
 		if($this->actiontype == 'CREATE') {
-			if($this->actionModule == 'HelpDesk' || $this->actionModule == 'HelpDeskNoContact') {
-				$returnid = $this->__CreateTicket($mailscanner, $mailrecord, $mailscannerrule);
-			} else if ($this->actionModule == 'Contacts') {
-				$returnid = $this->__CreateContact($mailscanner, $mailrecord, $mailscannerrule);
-			} else if ($this->actionModule == 'Leads') {
-				$returnid = $this->__CreateLead($mailscanner, $mailrecord, $mailscannerrule);
-			} else if ($this->actionModule == 'Accounts') {
-				$returnid = $this->__CreateAccount($mailscanner, $mailrecord, $mailscannerrule);
-			} else if ($this->actionModule == 'Potentials' || $this->actionModule == 'PotentialsNoContact') {
-				$returnid = $this->__CreatePotential($mailscanner, $mailrecord, $mailscannerrule);
+			if($this->module == 'HelpDesk') {
+				$returnid = $this->__CreateTicket($mailscanner, $mailrecord,$mailscannerrule);
+			} else if ($this->module == 'Contacts') {
+				$returnid = $this->__CreateContact($mailscanner, $mailrecord,$mailscannerrule);
+			} else if ($this->module == 'Leads') {
+				$returnid = $this->__CreateLead($mailscanner, $mailrecord,$mailscannerrule);
+			} else if ($this->module == 'Accounts') {
+				$returnid = $this->__CreateAccount($mailscanner, $mailrecord,$mailscannerrule);
 			}
 		} else if($this->actiontype == 'LINK') {
-			$focus = $this->getLinkFocusByRegexMatch($mailscanner, $mailrecord, $mailscannerrule->hasRegexMatch($matchresult));
-			if(!is_bool($focus)) {
-				$returnid = $this->__LinkToRecord($mailscanner, $mailrecord, $focus);
-			} else if($focus) {
-				$returnid = $this->__LinkToRecord($mailscanner, $mailrecord);
-			}
+			$returnid = $this->__LinkToRecord($mailscanner, $mailrecord);
 		} else if ($this->actiontype == 'UPDATE') {
-			if ($this->actionModule == 'HelpDesk') {
-				$returnid = $this->__UpdateTicket($mailscanner, $mailrecord, $mailscannerrule->hasRegexMatch($matchresult), $mailscannerrule);
+			if ($this->module == 'HelpDesk') {
+				$returnid = $this->__UpdateTicket($mailscanner, $mailrecord, $mailscannerrule->hasRegexMatch($matchresult),$mailscannerrule);
 			}
 		}
 		return $returnid;
 	}
 
-	/*
-	 * Function to get Ticket focus for Link Mail Action matching
-	 * "Regex" expression or "Has Ticket Number" condition.
-	 */
-	function getLinkFocusByRegexMatch($mailscanner, $mailrecord, $regexMatchInfo) {
-		if($this->actionModule == 'HelpDesk' && is_array($regexMatchInfo)) {
-			$record = $regexMatchInfo['matches'];
-			if($this->lookup == 'FROM')
-				$useemail = $mailrecord->_from;
-			else if($this->lookup == 'TO')
-				$useemail = $mailrecord->_to;
-
-			$focus = $mailscanner->GetTicketRecord($record);
-			foreach($useemail as $email) {
-				if($focus->column_fields['email'] == $email) {
-					return $focus;
-				}
-			}
-			return false;
-		}
-		return true;
-	}
-
 	/**
-	* Update ticket action.
-	*/
-		function __UpdateTicket($mailscanner, $mailrecord, $regexMatchInfo, $mailscannerrule) {
+	 * Update ticket action.
+	 */
+	function __UpdateTicket($mailscanner, $mailrecord, $regexMatchInfo,$mailscannerrule) {
 		global $adb;
 		$returnid = false;
 
@@ -193,67 +166,63 @@ class Vtiger_MailScannerAction {
 
 			// Get the ticket record that was created by SENDER earlier
 			$fromemail = $mailrecord->_from[0];
+
 			$linkfocus = $mailscanner->GetTicketRecord($usesubject, $fromemail);
-			$commentedBy = $mailscanner->LookupContact($fromemail);
-			if(!$commentedBy) {
-				$commentedBy = $mailscanner->LookupAccount($fromemail);
-			}
+            
+            $commentedBy = $mailscanner->LookupContact($fromemail);
+            if(!$commentedBy) {
+                $commentedBy = $mailscanner->LookupAccount($fromemail);
+            }
 
 			// If matching ticket is found, update comment, attach email
 			if($linkfocus) {
-				$recordModel = CRMEntity::getInstance('ModComments');
-				$recordModel->column_fields['commentcontent'] = $mailrecord->getParsedBody();
-				$recordModel->column_fields['related_to'] = $linkfocus->id;
-				$recordModel->column_fields['assigned_user_id'] = $linkfocus->column_fields['assigned_user_id'];
-				$recordModel->column_fields['from_mailconverter'] = true;
-				$recordModel->column_fields['from_portal'] = true;
-				if($commentedBy) {
-					$recordModel->column_fields['customer'] = $commentedBy;
-					$recordModel->column_fields['customer_email'] = $fromemail;
-					$recordModel->column_fields['userid'] = $linkfocus->column_fields['assigned_user_id'];
-				} else {
-					$recordModel->column_fields['customer_email'] = $fromemail;
-					$recordModel->column_fields['userid'] = $linkfocus->column_fields['assigned_user_id'];
-				}
-				$recordModel->save('ModComments');
+				$commentFocus = new ModComments();
+				$commentFocus->column_fields['commentcontent'] = $mailrecord->getBodyText();
+				$commentFocus->column_fields['related_to'] = $linkfocus->id;
+				$commentFocus->column_fields['assigned_user_id'] =  $mailscannerrule->assigned_to;
+                if($commentedBy) {
+                    $commentFocus->column_fields['customer'] = $commentedBy;
+                    $commentFocus->column_fields['from_mailconverter'] = 1;
+                } else {
+                    $commentFocus->column_fields['userid'] = $mailscannerrule->assigned_to;
+                }
+				$commentFocus->saveentity('ModComments');
+
 				// Set the ticket status to Open if its Closed
 				$adb->pquery("UPDATE vtiger_troubletickets set status=? WHERE ticketid=? AND status='Closed'", Array('Open', $linkfocus->id));
 
-				$returnid = $this->__CreateNewEmail($mailrecord, $this->actionModule, $linkfocus);
+				$returnid = $this->__CreateNewEmail($mailrecord, $this->module, $linkfocus);
+
+			} else {
+				// TODO If matching ticket was not found, create ticket?
+				// $returnid = $this->__CreateTicket($mailscanner, $mailrecord);
 			}
 		}
 		return $returnid;
-   }
+	}
 
 	/**
 	 * Create ticket action.
 	 */
 	function __CreateContact($mailscanner, $mailrecord, $mailscannerrule) {
-			if($mailscanner->LookupContact($mailrecord->_from[0]) && !Vtiger_MailScannerBodyRule::hasBodyRule($mailscannerrule->scannerid, $mailscannerrule->ruleid)) {
-				$this->lookup = 'FROM';
-				return $this->__LinkToRecord($mailscanner, $mailrecord);
-			}
-			$name = $this->getName($mailrecord);
-			$email = $mailrecord->_from[0];
-			$description = $mailrecord->getParsedBody();
-
-			$contact = CRMEntity::getInstance('Contacts');
-			$this->setDefaultValue('Contacts', $contact);
-			if(Vtiger_MailScannerBodyRule::hasBodyRule($mailscannerrule->scannerid, $mailscannerrule->ruleid) && $this->actionModule == 'Contacts') {
-				$this->applyBodyRule($mailscannerrule, $mailrecord, $contact);
-			} else {
-				$contact->column_fields['firstname'] = $name[0];
-				$contact->column_fields['lastname'] = $name[1];
-				$contact->column_fields['email'] = $email;
-				$contact->column_fields['description'] = $description;
-			}
-			$contact->column_fields['assigned_user_id'] = $mailscannerrule->assigned_to;
-			$contact->column_fields['source'] = "Mail Converter";
-			$contact->save('Contacts');
+        if($mailscanner->LookupContact($mailrecord->_from[0])) {
+            $this->lookup = 'FROM';
+            return $this->__LinkToRecord($mailscanner, $mailrecord);
+        }
+                $name = $this->getName($mailrecord);
+		$email = $mailrecord->_from[0];
+		$description = $mailrecord->getBodyText();
 
-			if($this->actionModule == 'Contacts') {
-				$this->linkMailToRecord($mailscanner, $mailrecord, $contact);
-			}
+		$contact = new Contacts();
+                $this->setDefaultValue('Contacts', $contact);
+		$contact->column_fields['firstname'] = $name[0];
+                $contact->column_fields['lastname'] = $name[1];
+		$contact->column_fields['email'] = $email;
+		$contact->column_fields['assigned_user_id'] =  $mailscannerrule->assigned_to;
+		$contact->column_fields['description'] = $description;
+		$contact->save('Contacts');
+
+		$this->__SaveAttachements($mailrecord, 'Contacts', $contact);
 
 		return $contact->id;
 	}
@@ -262,202 +231,152 @@ class Vtiger_MailScannerAction {
 	 * Create Lead action.
 	 */
 	function __CreateLead($mailscanner, $mailrecord, $mailscannerrule) {
-			if($mailscanner->LookupLead($mailrecord->_from[0]) && !Vtiger_MailScannerBodyRule::hasBodyRule($mailscannerrule->scannerid, $mailscannerrule->ruleid)) {
-				$this->lookup = 'FROM';
-				return $this->__LinkToRecord($mailscanner, $mailrecord);
-			}
-			$name = $this->getName($mailrecord);
-			$email = $mailrecord->_from[0];
-			$description = $mailrecord->getParsedBody();
-
-			$lead = CRMEntity::getInstance('Leads');
-			$this->setDefaultValue('Leads', $lead);
-			if(Vtiger_MailScannerBodyRule::hasBodyRule($mailscannerrule->scannerid, $mailscannerrule->ruleid)) {
-				$this->applyBodyRule($mailscannerrule, $mailrecord, $lead);
-			} else {
-				$lead->column_fields['firstname'] = $name[0];
-				$lead->column_fields['lastname'] = $name[1];
-				$lead->column_fields['email'] = $email;
-				$lead->column_fields['description'] = $description;
-			}
-			$lead->column_fields['assigned_user_id'] = $mailscannerrule->assigned_to;
-			$lead->column_fields['source'] = 'Mail Converter';
-			$lead->save('Leads');
+        if($mailscanner->LookupLead($mailrecord->_from[0])) {
+            $this->lookup = 'FROM';
+            return $this->__LinkToRecord($mailscanner, $mailrecord);
+        }
+		$name = $this->getName($mailrecord);
+		$email = $mailrecord->_from[0];
+		$description = $mailrecord->getBodyText();
 
-			$this->linkMailToRecord($mailscanner, $mailrecord, $lead);
+		$lead = new Leads();
+        $this->setDefaultValue('Leads', $lead);
+		$lead->column_fields['firstname'] = $name[0];
+        $lead->column_fields['lastname'] = $name[1];
+		$lead->column_fields['email'] = $email;
+		$lead->column_fields['assigned_user_id'] = $mailscannerrule->assigned_to;
+		$lead->column_fields['description'] = $description;
+		$lead->save('Leads');
 
-			return $lead->id;
+		$this->__SaveAttachements($mailrecord, 'Leads', $lead);
+
+		return $lead->id;
 	}
 
 	/**
 	 * Create Account action.
 	 */
 	function __CreateAccount($mailscanner, $mailrecord, $mailscannerrule) {
-			if($mailscanner->LookupAccount($mailrecord->_from[0]) && !Vtiger_MailScannerBodyRule::hasBodyRule($mailscannerrule->scannerid, $mailscannerrule->ruleid)) {
-				$this->lookup = 'FROM';
-				return $this->__LinkToRecord($mailscanner, $mailrecord);
-			}
-			$name = $this->getName($mailrecord);
-			$email = $mailrecord->_from[0];
-			$description = $mailrecord->getParsedBody();
-
-			$account = CRMEntity::getInstance('Accounts');
-			$this->setDefaultValue('Accounts', $account);
-			if(Vtiger_MailScannerBodyRule::hasBodyRule($mailscannerrule->scannerid, $mailscannerrule->ruleid)) {
-				$this->applyBodyRule($mailscannerrule, $mailrecord, $account);
-			} else {
-				$account->column_fields['accountname'] = $name[0].' '.$name[1];
-				$account->column_fields['email1'] = $email;
-				$account->column_fields['description'] = $description;
-			}
-			$account->column_fields['assigned_user_id'] = $mailscannerrule->assigned_to;
-			$account->column_fields['source'] = 'Mail Converter';
-			$account->save('Accounts');
-
-			$this->linkMailToRecord($mailscanner, $mailrecord, $account);
-
-			return $account->id;
-	}
-
-	/**
-	 * Create Potential action
-	 */
-	function __CreatePotential($mailscanner, $mailrecord, $mailscannerrule) {
+        if($mailscanner->LookupAccount($mailrecord->_from[0])) {
+            $this->lookup = 'FROM';
+            return $this->__LinkToRecord($mailscanner, $mailrecord);
+        }
+		$name = $this->getName($mailrecord);
 		$email = $mailrecord->_from[0];
-		$contactLinktoid = $mailscanner->LookupContact($email);
-		if(!$contactLinktoid && $this->actionModule == 'Potentials') {
-			$contactLinktoid = $this-> __CreateContact($mailscanner, $mailrecord, $mailscannerrule);
-		}
-		if ($contactLinktoid)
-			$linktoid = $mailscanner->getAccountId($contactLinktoid);
-		else
-			$linktoid = $mailscanner->LookupAccount($email);
-
-		$potential = CRMEntity::getInstance('Potentials');
-		$this->setDefaultValue('Potentials', $potential);
-		$potential->column_fields['closingdate'] = date('Y-m-d', strtotime('+1 day'));
-		if(Vtiger_MailScannerBodyRule::hasBodyRule($mailscannerrule->scannerid, $mailscannerrule->ruleid)) {
-			$this->applyBodyRule($mailscannerrule, $mailrecord, $potential);
-		} else {
-			$potential->column_fields['potentialname'] = $mailrecord->_subject;
-			$potential->column_fields['email'] = $email;
-			$potential->column_fields['description'] = $mailrecord->getParsedBody();
-		}
-		$potential->column_fields['assigned_user_id'] = $mailscannerrule->assigned_to;
-		$potential->column_fields['contact_id'] = $contactLinktoid;
-		$potential->column_fields['related_to'] = $linktoid;
-		$potential->column_fields['source'] = 'Mail Converter';
-		$potential->save('Potentials');
+		$description = $mailrecord->getBodyText();
+
+		$account = new Accounts();
+        $this->setDefaultValue('Accounts', $account);
+		$account->column_fields['accountname'] = $name[0].' '.$name[1];
+		$account->column_fields['email1'] = $email;
+		$account->column_fields['assigned_user_id'] =  $mailscannerrule->assigned_to;
+		$account->column_fields['description'] = $description;
+		$account->save('Accounts');
 
-		$this->linkMailToRecord($mailscanner, $mailrecord, $potential);
+		$this->__SaveAttachements($mailrecord, 'Accounts', $account);
 
-		return $potential->id;
+		return $account->id;
 	}
 
 	/**
 	 * Create ticket action.
 	 */
 	function __CreateTicket($mailscanner, $mailrecord, $mailscannerrule) {
-			// Prepare data to create trouble ticket
-			$usetitle = $mailrecord->_subject;
-			$description = $mailrecord->getParsedBody();
-
-			// There will be only on FROM address to email, so pick the first one
-			$fromemail = $mailrecord->_from[0];
-			$contactLinktoid = $mailscanner->LookupContact($fromemail);
-			if(!$contactLinktoid && $this->actionModule == 'HelpDesk') {
-				$contactLinktoid = $this-> __CreateContact($mailscanner, $mailrecord, $mailscannerrule);
-			}
-			if ($contactLinktoid)
-					$linktoid = $mailscanner->getAccountId($contactLinktoid);
-			if(!$linktoid)
-				$linktoid = $mailscanner->LookupAccount($fromemail);
-
-			// Create trouble ticket record
-			$ticket = CRMEntity::getInstance('HelpDesk');
-			$this->setDefaultValue('HelpDesk', $ticket);
-			if(Vtiger_MailScannerBodyRule::hasBodyRule($mailscannerrule->scannerid, $mailscannerrule->ruleid)) {
-				$this->applyBodyRule($mailscannerrule, $mailrecord, $ticket);
-			} else {
-				$ticket->column_fields['ticket_title'] = $usetitle;
-				$ticket->column_fields['description'] = $description;
-				$ticket->column_fields['email'] = $fromemail;
-			}
-			$ticket->column_fields['assigned_user_id'] = $mailscannerrule->assigned_to;
-			if ($contactLinktoid)
-					$ticket->column_fields['contact_id'] = $contactLinktoid;
-			if ($linktoid)
-					$ticket->column_fields['parent_id'] = $linktoid;
-
-			$ticket->column_fields['source'] = 'Mail Converter';
-			$ticket->save('HelpDesk');
-
-			$this->linkMailToRecord($mailscanner, $mailrecord, $ticket);
-
-			return $ticket->id;
-	}
-
-	/**
-	 * Function to Link Mail to Records after creation of record through Mail Converter
-	 */
-	function linkMailToRecord($mailscanner, $mailrecord, $focus) {
-		$this->lookup = 'FROM';
-		return $this->__LinkToRecord($mailscanner, $mailrecord, $focus);
+		// Prepare data to create trouble ticket
+		$usetitle = $mailrecord->_subject;
+		$description = $mailrecord->getBodyText();
+
+		// There will be only on FROM address to email, so pick the first one
+		$fromemail = $mailrecord->_from[0];
+		$contactLinktoid = $mailscanner->LookupContact($fromemail);
+        if(!$contactLinktoid) {
+            $contactLinktoid = $this-> __CreateContact($mailscanner, $mailrecord, $mailscannerrule);
+        }
+		if ($contactLinktoid)
+			$linktoid = $mailscanner->getAccountId($contactLinktoid);
+        if(!$linktoid)
+                $linktoid = $mailscanner->LookupAccount($fromemail);
+
+		// Create trouble ticket record
+		$ticket = new HelpDesk();
+                $this->setDefaultValue('HelpDesk', $ticket);
+		if(empty($ticket->column_fields['ticketstatus']) || $ticket->column_fields['ticketstatus'] == '?????')
+                    $ticket->column_fields['ticketstatus'] = 'Open';
+                $ticket->column_fields['ticket_title'] = $usetitle;
+		$ticket->column_fields['description'] = $description;
+		$ticket->column_fields['assigned_user_id'] =  $mailscannerrule->assigned_to;
+		if ($contactLinktoid)
+			$ticket->column_fields['contact_id'] = $contactLinktoid;
+		if ($linktoid)
+			$ticket->column_fields['parent_id'] = $linktoid;
+		$ticket->save('HelpDesk');
+
+		// Associate any attachement of the email to ticket
+		$this->__SaveAttachements($mailrecord, 'HelpDesk', $ticket);
+                
+                if($contactLinktoid)
+                    $relatedTo = $contactLinktoid;
+                else
+                    $relatedTo = $linktoid;
+                $this->linkMail($mailscanner, $mailrecord, $relatedTo);
+                
+		return $ticket->id;
 	}
-
-	/**
+        
+        /**
+         * Function to link email record to contact/account/lead
+         * record if exists with same email id
+         * @param type $mailscanner
+         * @param type $mailrecord
+         */
+        function linkMail($mailscanner, $mailrecord, $relatedTo) {
+            $fromemail = $mailrecord->_from[0];
+            
+            $linkfocus = $mailscanner->GetContactRecord($fromemail, $relatedTo);
+            $module = 'Contacts';
+            if(!$linkfocus) {
+                $linkfocus = $mailscanner->GetAccountRecord($fromemail, $relatedTo);
+                $module = 'Accounts';
+            }
+
+            if($linkfocus) {
+                $this->__CreateNewEmail($mailrecord, $module, $linkfocus);
+            }
+        }
+
+        /**
 	 * Add email to CRM record like Contacts/Accounts
 	 */
-	function __LinkToRecord($mailscanner, $mailrecord, $linkfocus = false) {
+	function __LinkToRecord($mailscanner, $mailrecord) {
+		$linkfocus = false;
+
 		$useemail  = false;
 		if($this->lookup == 'FROM') $useemail = $mailrecord->_from;
 		else if($this->lookup == 'TO') $useemail = $mailrecord->_to;
 
-		if($this->actionModule == 'PotentialsNoContact') {
-			$module = 'Potentials';
-		} else if($this->actionModule == 'HelpDeskNoContact') {
-			$module = 'HelpDesk';
-		} else {
-			$module = $this->actionModule;
-		}
-
-		if(!$linkfocus) {
-			if ($module == 'Contacts') {
-				foreach ($useemail as $email) {
-					$linkfocus = $mailscanner->GetContactRecord($email);
-					if ($linkfocus)
-						break;
-				}
-			} else if ($module == 'Accounts') {
-				foreach ($useemail as $email) {
-					$linkfocus = $mailscanner->GetAccountRecord($email);
-					if ($linkfocus)
-						break;
-				}
-			} else if ($module == 'Leads') {
-				foreach ($useemail as $email) {
-					$linkfocus = $mailscanner->GetLeadRecord($email);
-					if ($linkfocus)
-						break;
-				}
-			} else if ($module == 'Potentials') {
-				foreach ($useemail as $email) {
-					$linkfocus = $mailscanner->GetPotentialRecord($email);
-					if ($linkfocus)
-						break;
-				}
-			} else if ($module == 'HelpDesk') {
-				foreach ($useemail as $email) {
-					$linkfocus = $mailscanner->GetTicketFocus($email);
-					if ($linkfocus)
-						break;
-				}
+		if ($this->module == 'Contacts') {
+			foreach ($useemail as $email) {
+				$linkfocus = $mailscanner->GetContactRecord($email);
+				if ($linkfocus)
+					break;
+			}
+		} else if ($this->module == 'Accounts') {
+			foreach ($useemail as $email) {
+				$linkfocus = $mailscanner->GetAccountRecord($email);
+				if ($linkfocus)
+					break;
+			}
+		} else if ($this->module == 'Leads') {
+			foreach ($useemail as $email) {
+				$linkfocus = $mailscanner->GetLeadRecord($email);
+				if ($linkfocus)
+					break;
 			}
 		}
 
 		$returnid = false;
 		if($linkfocus) {
-			$returnid = $this->__CreateNewEmail($mailrecord, $module, $linkfocus);
+			$returnid = $this->__CreateNewEmail($mailrecord, $this->module, $linkfocus);
 		}
 		return $returnid;
 	}
@@ -467,21 +386,15 @@ class Vtiger_MailScannerAction {
 	 */
 	function __CreateNewEmail($mailrecord, $module, $linkfocus) {
 		global $current_user, $adb;
-		//get mail scanner info to save mail box email id
-		$scannerId = $this->scannerid;
-		include_once 'modules/Settings/MailConverter/handlers/MailScannerInfo.php';
-		include_once 'modules/Settings/MailConverter/handlers/MailBox.php';
-		$scannerName = Settings_MailConverter_Module_Model::getScannerName($scannerId);
-		$scannerInfo = new Vtiger_MailScannerInfo($scannerName);
 		if(!$current_user) {
 			$current_user = Users::getActiveAdminUser();
 		}
-		$assignedToId = $linkfocus->column_fields['assigned_user_id'];
-		if(vtws_getOwnerType($assignedToId) == 'Groups') {
-			$assignedToId = Users::getActiveAdminId();
-		}
-
-		$focus = CRMEntity::getInstance('Emails');
+        $assignedToId = $linkfocus->column_fields['assigned_user_id'];
+        if(vtws_getOwnerType($assignedToId) == 'Groups') {
+            $assignedToId = Users::getActiveAdminId();
+        }
+        
+		$focus = new Emails();
 		$focus->column_fields['parent_type'] = $module;
 		$focus->column_fields['activitytype'] = 'Emails';
 		$focus->column_fields['parent_id'] = "$linkfocus->id@-1|";
@@ -490,19 +403,19 @@ class Vtiger_MailScannerAction {
 		$focus->column_fields['description'] = $mailrecord->getBodyHTML();
 		$focus->column_fields['assigned_user_id'] = $assignedToId;
 		$focus->column_fields["date_start"] = date('Y-m-d', $mailrecord->_date);
-		$focus->column_fields["time_start"] = date('H:i:s', $mailrecord->_date);
+		$focus->column_fields["time_start"] = gmdate("H:i:s");
 		$focus->column_fields["email_flag"] = 'MAILSCANNER';
 
 		$from=$mailrecord->_from[0];
 		$to = $mailrecord->_to[0];
 		$cc = (!empty($mailrecord->_cc))? implode(',', $mailrecord->_cc) : '';
 		$bcc= (!empty($mailrecord->_bcc))? implode(',', $mailrecord->_bcc) : '';
+		$flag=''; // 'SENT'/'SAVED'
 		//emails field were restructured and to,bcc and cc field are JSON arrays
 		$focus->column_fields['from_email'] = $from;
 		$focus->column_fields['saved_toid'] = $to;
 		$focus->column_fields['ccmail'] = $cc;
 		$focus->column_fields['bccmail'] = $bcc;
-		$focus->column_fields['mailboxemail'] = $scannerInfo->username;
 		$focus->save('Emails');
 
 		$emailid = $focus->id;
@@ -511,8 +424,6 @@ class Vtiger_MailScannerAction {
 		// TODO: Handle attachments of the mail (inline/file)
 		$this->__SaveAttachements($mailrecord, 'Emails', $focus);
 
-				// To add entry in ModTracker for email relation
-				relateEntities($linkfocus, $module, $linkfocus->id, 'Emails', $emailid);
 		return $emailid;
 	}
 
@@ -543,7 +454,7 @@ class Vtiger_MailScannerAction {
 			$issaved = $this->__SaveAttachmentFile($attachid, $filename, $filecontent);
 			if($issaved) {
 				// Create document record
-				$document = CRMEntity::getInstance('Documents');
+				$document = new Documents();
 				$document->column_fields['notes_title']		 = $filename;
 				$document->column_fields['filename']		 = $filename;
 				$document->column_fields['filesize']		 = mb_strlen($filecontent, '8bit');
@@ -554,14 +465,21 @@ class Vtiger_MailScannerAction {
 				$document->save('Documents');
 
 				// Link file attached to document
-				$adb->pquery("INSERT INTO vtiger_seattachmentsrel(crmid, attachmentsid) VALUES(?,?)", Array($document->id, $attachid));
+				$adb->pquery("INSERT INTO vtiger_seattachmentsrel(crmid, attachmentsid) VALUES(?,?)",
+					Array($document->id, $attachid));
 
 				// Link document to base record
-				$adb->pquery("INSERT INTO vtiger_senotesrel(crmid, notesid) VALUES(?,?)", Array($basefocus->id, $document->id));
+				$adb->pquery("INSERT INTO vtiger_senotesrel(crmid, notesid) VALUES(?,?)",
+					Array($basefocus->id, $document->id));
 
 				// Link document to Parent entity - Account/Contact/...
 				list($eid,$junk)=explode('@',$basefocus->column_fields['parent_id']);
-				$adb->pquery("INSERT INTO vtiger_senotesrel(crmid, notesid) VALUES(?,?)", Array($eid, $document->id));
+				$adb->pquery("INSERT INTO vtiger_senotesrel(crmid, notesid) VALUES(?,?)",
+					Array($eid, $document->id));
+
+				// Link Attachement to the Email
+				$adb->pquery("INSERT INTO vtiger_seattachmentsrel(crmid, attachmentsid) VALUES(?,?)",
+					Array($basefocus->id, $attachid));
 			}
 		}
 	}
@@ -573,25 +491,18 @@ class Vtiger_MailScannerAction {
 		global $adb;
 
 		$dirname = $this->STORAGE_FOLDER;
-		//To get group permissions given to config.inc.php file
-		$permissions = Vtiger_Functions::getGroupPermissionsFromConfigFile();
-		if(!is_dir($dirname)){
-			mkdir($dirname);
-			// Giving group permissions to newly created directory
-			exec("chown -R $permissions $dirname");
-		}
+		if(!is_dir($dirname)) mkdir($dirname);
 
 		$description = $filename;
 		$filename = str_replace(' ', '-', $filename);
 		$saveasfile = "$dirname$attachid" . "_$filename";
 		if(!file_exists($saveasfile)) {
+
 			$this->log("Saved attachement as $saveasfile\n");
 
 			$fh = fopen($saveasfile, 'wb');
 			fwrite($fh, $filecontent);
 			fclose($fh);
-			// Giving group permissions to newly created directory
-			exec("chown -R $permissions $saveasfile");
 		}
 
 		$mimetype = MailAttachmentMIME::detect($saveasfile);
@@ -601,69 +512,49 @@ class Vtiger_MailScannerAction {
 
 		return true;
 	}
-
-	function setDefaultValue($module, $moduleObj) { 
-		$moduleInstance = Vtiger_Module_Model::getInstance($module);
-
-		$fieldInstances = Vtiger_Field_Model::getAllForModule($moduleInstance);
-		foreach($fieldInstances as $blockInstance) {
-			foreach($blockInstance as $fieldInstance) {
-				$fieldName = $fieldInstance->getName();
-				$defaultValue = $fieldInstance->getDefaultFieldValue();
-				if($defaultValue) {
-					$moduleObj->column_fields[$fieldName] = decode_html($defaultValue);
-				}
-				if($fieldInstance->isMandatory() && !$defaultValue) {
-					if($fieldInstance->getFieldDataType() == 'picklist' || $fieldInstance->getFieldDataType() == 'multipicklist') {
-						$picklistValues = $fieldInstance->getPicklistValues();
-						$randomValue = reset($picklistValues);
-						if($randomValue)
-							$moduleObj->column_fields[$fieldName] = $randomValue;
-					} else {
-						$moduleObj->column_fields[$fieldName] = Vtiger_Util_Helper::getDefaultMandatoryValue($fieldInstance->getFieldDataType());
-					}
-				}
-			}
-		}
-	}
-
-	/**
-	 * Function to get Mail Sender's Name
-	 * @param <Vtiger_MailRecord Object> $mailrecord
-	 * @return <Array> containing First Name and Last Name
-	 */
-	function getName($mailrecord) {
-		$name = $mailrecord->_fromname;
-		if(!empty($name)) {
-			$nameParts = explode(' ', $name);
-			if(count($nameParts) > 1) {
-				$firstName = $nameParts[0];
-				unset($nameParts[0]);
-				$lastName = implode(' ', $nameParts);
-			} else {
-				$firstName = '';
-				$lastName = $nameParts[0];
-			}
-		} else {
-			$firstName = '';
-			$lastName = $mailrecord->_from[0];
-		}
-
-		return array($firstName, $lastName);
-	}
-
-	function applyBodyRule($mailscannerrule, $mailrecord, $focus) {
-		$bodyRule = new Vtiger_MailScannerBodyRule($mailscannerrule->scannerid, $mailscannerrule->ruleid);
-		if($bodyRule->ruleId) {
-			$bodyRule->fromemail = $mailrecord->_from[0];
-			$bodyRule->subject = $mailrecord->_subject;
-			$name = $this->getName($mailrecord);
-			$bodyRule->fromname = implode(' ', $name);
-			$bodyFields = $bodyRule->getFieldValues($mailrecord->getParsedBody());
-			foreach($bodyFields as $fieldName => $fieldValue) {
-				$focus->column_fields[$fieldName] = $fieldValue;
-			}
-		}
-	}
+    
+    function setDefaultValue($module, $moduleObj) { 
+        $moduleInstance = Vtiger_Module_Model::getInstance($module);
+        
+        $fieldInstances = Vtiger_Field_Model::getAllForModule($moduleInstance);
+        foreach($fieldInstances as $blockInstance) {
+            foreach($blockInstance as $fieldInstance) {
+                $fieldName = $fieldInstance->getName();
+                $defaultValue = $fieldInstance->getDefaultFieldValue();
+                if($defaultValue) {
+                    $moduleObj->column_fields[$fieldName] = decode_html($defaultValue);
+                }
+                if($fieldInstance->isMandatory() && !$defaultValue) {
+                    $moduleObj->column_fields[$fieldName] = Vtiger_Util_Helper::getDefaultMandatoryValue($fieldInstance->getFieldDataType());
+                }
+            }
+        }
+    }
+    
+    /**
+     * Function to get Mail Sender's Name
+     * @param <Vtiger_MailRecord Object> $mailrecord
+     * @return <Array> containing First Name and Last Name
+     */
+    function getName($mailrecord) {
+        $name = $mailrecord->_fromname;
+        if(!empty($name)) {
+            $nameParts = explode(' ', $name);
+            if(count($nameParts) > 1) {
+                $firstName = $nameParts[0];
+                unset($nameParts[0]);
+                $lastName = implode(' ', $nameParts);
+            } else {
+                $firstName = '';
+                $lastName = $nameParts[0];
+            }
+        } else {
+            $firstName = '';
+            $lastName = $mailrecord->_from[0];
+        }
+        
+        return array($firstName, $lastName);
+    }
+    
 }
 ?>
diff --git a/modules/Settings/MailConverter/handlers/MailScannerInfo.php b/modules/Settings/MailConverter/handlers/MailScannerInfo.php
index 2e34aff3634eda54eb9f3dea48957da5a78498f4..8bb3a62037bd4fdba83bbcd50e314799abbd96dd 100644
--- a/modules/Settings/MailConverter/handlers/MailScannerInfo.php
+++ b/modules/Settings/MailConverter/handlers/MailScannerInfo.php
@@ -38,8 +38,6 @@ class Vtiger_MailScannerInfo {
 	var $markas = false;
 	// server time_zone
 	var $time_zone = false;
-    // scan all mails or mails from yesterday
-    var $scanfrom = false;
 
 	// is the scannered enabled?
 	var $isvalid   = false;
@@ -80,7 +78,7 @@ class Vtiger_MailScannerInfo {
 
 		if($adb->num_rows($result)) {
 			$this->scannerid  = $adb->query_result($result, 0, 'scannerid');
-			$this->scannername= decode_html($adb->query_result($result, 0, 'scannername'));
+			$this->scannername= $adb->query_result($result, 0, 'scannername');
 			$this->server     = $adb->query_result($result, 0, 'server');
 			$this->protocol   = $adb->query_result($result, 0, 'protocol');
 			$this->username   = $adb->query_result($result, 0, 'username');
@@ -91,7 +89,6 @@ class Vtiger_MailScannerInfo {
 			$this->connecturl = $adb->query_result($result, 0, 'connecturl');
 			$this->searchfor  = $adb->query_result($result, 0, 'searchfor');
 			$this->markas     = $adb->query_result($result, 0, 'markas');
-            $this->scanfrom   = $adb->query_result($result, 0, 'scanfrom');
 			$this->isvalid    = $adb->query_result($result, 0, 'isvalid');
 			$this->time_zone   = $adb->query_result($result, 0, 'time_zone');
 
@@ -112,7 +109,7 @@ class Vtiger_MailScannerInfo {
 			$lastscancount = $adb->num_rows($lastscanres);
 			if($lastscancount) {
 				for($lsindex = 0; $lsindex < $lastscancount; ++$lsindex) {
-					$folder = decode_html($adb->query_result($lastscanres, $lsindex, 'foldername'));
+					$folder = $adb->query_result($lastscanres, $lsindex, 'foldername');
 					$scannedon =$adb->query_result($lastscanres, $lsindex, 'lastscan');
 					$nextrescan =$adb->query_result($lastscanres, $lsindex, 'rescan');
 					$this->lastscan[$folder] = $scannedon;
@@ -148,7 +145,8 @@ class Vtiger_MailScannerInfo {
 
 	function dateBasedOnMailServerTimezone($format='d-M-Y') {
 		$returnDate = NULL;
-		if ($this->time_zone && trim($this->time_zone)) {
+		##--Fix for trac : http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/8051-## 
+                if ($this->timezone && trim($this->timezone)) { 
 			$currentTZ = date_default_timezone_get();
 			list ($tzhours, $tzminutes) = explode(':', trim($this->time_zone));
 			$returnDate = date($format, strtotime(sprintf("%s hours %s minutes", $tzhours, $tzminutes)));
@@ -234,7 +232,7 @@ class Vtiger_MailScannerInfo {
 			if($fldcount) {
 				$folderinfo = Array();
 				for($index = 0; $index < $fldcount; ++$index) {
-					$foldername = decode_html($adb->query_result($fldres, $index, 'foldername'));
+					$foldername = $adb->query_result($fldres, $index, 'foldername');
 					$folderid   = $adb->query_result($fldres, $index, 'folderid');
 					$lastscan   = $adb->query_result($fldres, $index, 'lastscan');
 					$rescan     = $adb->query_result($fldres, $index, 'rescan');
@@ -305,7 +303,7 @@ class Vtiger_MailScannerInfo {
 	function getAsMap() {
 		$infomap = Array();
 		$keys = Array('scannerid', 'scannername', 'server', 'protocol', 'username', 'password', 'ssltype',
-			'sslmethod', 'connecturl', 'searchfor', 'markas', 'scanfrom', 'isvalid', 'time_zone', 'rules');
+			'sslmethod', 'connecturl', 'searchfor', 'markas', 'isvalid', 'time_zone', 'rules');
 		foreach($keys as $key) {
 			$infomap[$key] = $this->$key;
 		}
@@ -347,7 +345,6 @@ class Vtiger_MailScannerInfo {
 		$this->connecturl= $otherInstance->connecturl;
 		$this->searchfor = $otherInstance->searchfor;
 		$this->markas    = $otherInstance->markas;
-        $this->scanfrom  = $otherInstance->scanfrom;
 		$this->isvalid   = $otherInstance->isvalid;
 		$this->time_zone  = $otherInstance->time_zone;
 
@@ -358,16 +355,15 @@ class Vtiger_MailScannerInfo {
 		global $adb;
 		if($this->scannerid == false) {
             $adb->pquery("INSERT INTO vtiger_mailscanner(scannername,server,protocol,username,password,ssltype,
-				sslmethod,connecturl,searchfor,markas,isvalid,time_zone,scanfrom) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
+				sslmethod,connecturl,searchfor,markas,isvalid,time_zone) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)",
 				Array($this->scannername,$this->server, $this->protocol, $this->username, $usepassword,
-				$this->ssltype, $this->sslmethod, $this->connecturl, $this->searchfor, $this->markas, $useisvalid, $this->time_zone, $this->scanfrom));
+				$this->ssltype, $this->sslmethod, $this->connecturl, $this->searchfor, $this->markas, $useisvalid, $this->time_zone));
 			$this->scannerid = $adb->database->Insert_ID();
-            
         } else { //this record is exist in the data
 			$adb->pquery("UPDATE vtiger_mailscanner SET scannername=?,server=?,protocol=?,username=?,password=?,ssltype=?,
-				sslmethod=?,connecturl=?,searchfor=?,markas=?,isvalid=?, time_zone=?, scanfrom = ? WHERE scannerid=?",
+				sslmethod=?,connecturl=?,searchfor=?,markas=?,isvalid=?, time_zone=? WHERE scannerid=?",
 				Array($this->scannername,$this->server,$this->protocol, $this->username, $usepassword, $this->ssltype,
-				$this->sslmethod, $this->connecturl,$this->searchfor, $this->markas,$useisvalid, $this->time_zone, $this->scanfrom, $this->scannerid));
+				$this->sslmethod, $this->connecturl,$this->searchfor, $this->markas,$useisvalid, $this->time_zone, $this->scannerid));
         }
 
 		return $mailServerChanged;
@@ -389,9 +385,8 @@ class Vtiger_MailScannerInfo {
 		if($this->scannerid) {
 			$tables = Array(
 				'vtiger_mailscanner',
-				'vtiger_mailscanner_folders',
-                'vtiger_mailscanner_bodyrule',
-                'vtiger_mailscanner_mapping'
+				'vtiger_mailscanner_ids',
+				'vtiger_mailscanner_folders'
 			);
 			foreach($tables as $table) {
 				$adb->pquery("DELETE FROM $table WHERE scannerid=?", Array($this->scannerid));
diff --git a/modules/Settings/MailConverter/handlers/MailScannerRule.php b/modules/Settings/MailConverter/handlers/MailScannerRule.php
index 118b5604c57a1e992adc74a7aa4d364759c34d1b..4dc0ece49bd78ca1117904e07e296cee801d2613 100644
--- a/modules/Settings/MailConverter/handlers/MailScannerRule.php
+++ b/modules/Settings/MailConverter/handlers/MailScannerRule.php
@@ -16,7 +16,7 @@ require_once('modules/Settings/MailConverter/handlers/MailScannerAction.php');
  */
 class Vtiger_MailScannerRule {
     // id of this instance
-	var $ruleid    = false;	
+	var $ruleid    = false;
     // scanner to which this rule is linked
     var $scannerid = false;
     // from address criteria
@@ -35,7 +35,7 @@ class Vtiger_MailScannerRule {
 	var $bodyop    = false;
     // body criteria
 	var $body      = false;
-    // order of this rule 
+    // order of this rule
 	var $sequence  = false;
     // is this action valid
 	var $isvalid   = false;
@@ -168,9 +168,9 @@ class Vtiger_MailScannerRule {
             }
         } else {
             $matchfound = false;
-            if($this->matchusing == 'OR') {
-                $matchfound = true;
-                $matchresults[] = $this->__CreateMatchResult('BLANK','','','');
+                if($this->matchusing == 'OR') {
+            $matchfound = true;
+                    $matchresults[] = $this->__CreateMatchResult('BLANK','','','');
             }
         }
 		return ($matchfound)? $matchresults : false;
@@ -206,41 +206,35 @@ class Vtiger_MailScannerRule {
                 }
                 break;
             case 'TO':
-                if($this->toaddress) {
-                    if(strpos($this->toaddress, '*') == 0)
-                        $this->toaddress = trim($this->toaddress, '*');
-                    foreach($mailrecord->_to as $toemail) {
-                        $matchfound = $this->find($subrule, 'Contains', $toemail, $this->toaddress);
-                            if($matchfound) break;
-                    }
+                        if($this->toaddress) {
+                            foreach($mailrecord->_to as $toemail) {
+                    $matchfound = $this->find($subrule, 'Contains', $toemail, $this->toaddress);
+                                if($matchfound) break;
+                }
                 } else {
-                    $matchfound = $this->__CreateDefaultMatchResult($subrule);
+                $matchfound = $this->__CreateDefaultMatchResult($subrule);
                 }
                 break;
             case 'CC':
                 if ($this->cc) {
-                    if(strpos($this->cc, '*') == 0)
-                        $this->cc = trim($this->cc, '*');
-                    foreach ($mailrecord->_cc as $toemail) {
-                        $matchfound = $this->find($subrule, 'Contains', $toemail, $this->cc);
-                        if ($matchfound) 
-                            break;
-                    }
+                foreach ($mailrecord->_cc as $toemail) {
+                    $matchfound = $this->find($subrule, 'Contains', $toemail, $this->cc);
+                    if ($matchfound)
+                    break;
+                }
                 } else {
-                    $matchfound = $this->__CreateDefaultMatchResult($subrule);
+                $matchfound = $this->__CreateDefaultMatchResult($subrule);
                 }
                 break;
             case 'BCC':
                 if ($this->bcc) {
-                    if(strpos($this->bcc, '*') == 0)
-                        $this->bcc = trim($this->bcc, '*');
-                    foreach ($mailrecord->_bcc as $toemail) {
-                        $matchfound = $this->find($subrule, 'Contains', $toemail, $this->bcc);
-                        if ($matchfound)
-                            break;
-                    }
+                foreach ($mailrecord->_bcc as $toemail) {
+                    $matchfound = $this->find($subrule, 'Contains', $toemail, $this->bcc);
+                    if ($matchfound)
+                    break;
+                }
                 } else {
-                    $matchfound = $this->__CreateDefaultMatchResult($subrule);
+                $matchfound = $this->__CreateDefaultMatchResult($subrule);
                 }
                 break;
             case 'SUBJECT':
@@ -252,9 +246,9 @@ class Vtiger_MailScannerRule {
                 break;
             case 'BODY':
                 if ($this->bodyop) {
-                    $matchfound = $this->find($subrule, $this->bodyop, $mailrecord->getBodyText(), trim($this->body));
+                $matchfound = $this->find($subrule, $this->bodyop, trim(strip_tags($mailrecord->_body)), trim($this->body));
                 } else {
-                    $matchfound = $this->__CreateDefaultMatchResult($subrule);
+                $matchfound = $this->__CreateDefaultMatchResult($subrule);
                 }
                 break;
             }
@@ -268,8 +262,8 @@ class Vtiger_MailScannerRule {
     function find($subrule, $condition, $input, $searchfor) {
         if (!$input)
             return false;
-        $input = trim(preg_replace("/\r/", '', decode_html($input)));
-        $searchfor = decode_html($searchfor);
+            $input = trim(preg_replace("/\r/", '', decode_html($input))); 
+            $searchfor = decode_html($searchfor);
         $matchfound = false;
         $matches = false;
 
@@ -318,7 +312,7 @@ class Vtiger_MailScannerRule {
             case 'Has Ticket Number':
             $regmatches = Array();
             $matchfound = false;
-            $searchfor = "Ticket Id[^:]?: ([0-9]+)";
+            $searchfor = "Ticket Id[^:]?: ([0-9]+)"; 
             $searchfor = str_replace('/', '\/', $searchfor);
             if (preg_match("/$searchfor/i", $input, $regmatches)) {
                 // Pick the last matching group
@@ -355,7 +349,7 @@ class Vtiger_MailScannerRule {
 		foreach($matchresult as $matchinfo) {
             $match_condition = $matchinfo['condition'];
             $match_string = $matchinfo['matches'];
-                if(($match_condition == 'Regex' || $match_condition == 'Has Ticket Number') && $match_string)
+                if(($match_condition == 'Regex' || $match_condition == 'Has Ticket Number') && $match_string) 
             return $matchinfo;
         }
         return false;
@@ -390,7 +384,7 @@ class Vtiger_MailScannerRule {
             $this->bodyop, $this->body, $this->matchusing, $this->assigned_to, $this->cc, $this->bcc, $this->ruleid));
         } else {
             $this->sequence = $this->__nextsequence();
-            $adb->pquery("INSERT INTO vtiger_mailscanner_rules(scannerid,fromaddress,toaddress,subjectop,subject,bodyop,body,matchusing,sequence,assigned_to,cc,bcc) 
+            $adb->pquery("INSERT INTO vtiger_mailscanner_rules(scannerid,fromaddress,toaddress,subjectop,subject,bodyop,body,matchusing,sequence,assigned_to,cc,bcc)
                     VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array($this->scannerid, $this->fromaddress, $this->toaddress, $this->subjectop, $this->subject,
             $this->bodyop, $this->body, $this->matchusing, $this->sequence, $this->assigned_to, $this->cc, $this->bcc));
             $this->ruleid = $adb->database->Insert_ID();
@@ -426,8 +420,6 @@ class Vtiger_MailScannerRule {
             if($this->ruleid) {
             $adb->pquery("DELETE FROM vtiger_mailscanner_ruleactions WHERE ruleid = ?", Array($this->ruleid));
             $adb->pquery("DELETE FROM vtiger_mailscanner_rules WHERE ruleid=?", Array($this->ruleid));
-            $adb->pquery("DELETE FROM vtiger_mailscanner_bodyrule WHERE ruleid = ? AND scannerid = ?", array($this->ruleid, $this->scannerid));
-            $adb->pquery("DELETE FROM vtiger_mailscanner_mapping WHERE ruleid = ? AND scannerid = ?", array($this->ruleid, $this->scannerid));
         }
     }
 
@@ -458,23 +450,6 @@ class Vtiger_MailScannerRule {
         return $action->apply($mailscanner, $mailrecord, $this, $matchresult);
     }
 
-    /**
-     * Function to get number of rules currently exist(for CronTx)
-     * @global type $adb
-     * @param type $scannerId
-     * @return type
-     */
-    static function getNoOfRules($scannerId = false){
-        global $adb;
-        $query = "SELECT count(*) as count FROM vtiger_mailscanner_rules";
-        if($scannerId){
-            $query = "$query where scannerid = $scannerId";
-        }
-		$result = $adb->pquery($query, array());
-        $count = $adb->query_result($result,0,'count');
-        return $count;
-    }
-
 }
 
-?>
\ No newline at end of file
+?>
diff --git a/modules/Settings/MailConverter/models/Field.php b/modules/Settings/MailConverter/models/Field.php
index 404aac28e5c21785bcbfa7cd22b9ed507661df9e..e5701016f94a68620b443ce1776cbbf8432ecdf4 100644
--- a/modules/Settings/MailConverter/models/Field.php
+++ b/modules/Settings/MailConverter/models/Field.php
@@ -52,30 +52,18 @@ class Settings_MailConverter_Field_Model extends Vtiger_Field_Model {
         $fieldName = $this->getName();
         $pickListValues = array();
         if($fieldName == 'searchfor') {
-            $optionList = array('UNSEEN', 'ALL');
+            $optionList = array('ALL','UNSEEN');
             foreach($optionList as $option) {
                 $pickListValues[$option] = vtranslate($option, 'Settings::MailConverter');
             }
         }else if ($fieldName == 'markas') {
-            $optionList = array('SEEN', 'UNSEEN');
+            $optionList = array('UNSEEN','SEEN');
             foreach($optionList as $option) {
 				$pickListValues[$option] = vtranslate($option, 'Settings::MailConverter');
             }
         }else if ($fieldName == 'time_zone') {
             $pickListValues = self::$timeZonePickListValues;
-        } else if($fieldName == 'scanfrom') {
-            $optionList = array('YESTERDAY', 'ALL');
-            foreach($optionList as $option) {
-				$pickListValues[$option] = vtranslate($option, 'Settings::MailConverter');
-            }
-        } else if($fieldName == 'servertype') {
-            $pickListValues = array(
-                '' => 'Select Server Type',
-                'imap.gmail.com' => 'Gmail',
-                'imap.mail.yahoo.com' => 'Yahoo',
-                'mail.messagingengine.com' => 'Fastmail',
-                'other' => 'Other'
-            );
+            
         }
         return $pickListValues;
     }
diff --git a/modules/Settings/MailConverter/models/Module.php b/modules/Settings/MailConverter/models/Module.php
index 434a8796e0274e3c7d09349d4c6d628e8d99287f..dbaf3349e64e81222c2c7c18a414e9ed10970fae 100644
--- a/modules/Settings/MailConverter/models/Module.php
+++ b/modules/Settings/MailConverter/models/Module.php
@@ -11,15 +11,6 @@
 class Settings_MailConverter_Module_Model extends Settings_Vtiger_Module_Model {
 
 	var $name = 'MailConverter';
-    
-    //Overridden table names and fields
-    
-    var $baseTable = 'vtiger_mailscanner';
-    var $baseTableIndex = 'scannerid';
-    var $fieldName = 'scannername';
-    var $scannedFoldersTable = 'vtiger_mailscanner_folders';
-    var $scannerRulesTable = 'vtiger_mailscanner_rules';
-    var $scannerIdsTable = 'vtiger_message_ids';
 
 	/**
 	 * Function to get Create record url
@@ -37,7 +28,6 @@ class Settings_MailConverter_Module_Model extends Settings_Vtiger_Module_Model {
 	public function getFields() {
 		$fields =  array(
                 'scannername' => array('name' => 'scannername','typeofdata'=>'V~M','label'=>'Scanner Name','datatype'=>'string'),
-                'servertype' => array('name' => 'servertype','typeofdata'=>'V~M','label'=>'Server Type','datatype'=>'picklist'),
                 'server'      => array('name' => 'server','typeofdata'=>'V~M','label'=>'Server','datatype'=>'string'),
                 'username'    => array('name' => 'username','typeofdata'=>'V~M','label'=>'User Name','datatype'=>'string') ,
                 'password'    => array('name' => 'password','typeofdata'=>'V~M','label'=>'Password','datatype'=>'password') ,
@@ -47,9 +37,8 @@ class Settings_MailConverter_Module_Model extends Settings_Vtiger_Module_Model {
                 'connecturl'  => array('name' => 'connecturl', 'typeofdata'=>'V~O','label' => 'Connect URL','datatype' => 'string','isEditable'=>false),
                 'searchfor'   => array('name' => 'searchfor', 'typeofdata'=>'V~O','label'=>'Look For','datatype'=>'picklist'),
                 'markas'      => array('name' => 'markas', 'typeofdata'=>'V~O','label'=>'After Scan','datatype'=>'picklist'),
-                'scanfrom'    => array('name' => 'scanfrom', 'typeofdata'=>'V~O','label'=>'Scan From','datatype'=>'picklist'),
                 'isvalid'     => array('name' => 'isvalid', 'typeofdata'=>'C~O','label'=>'Status','datatype'=>'boolean'),
-                'time_zone'   => array('name' => 'time_zone', 'typeofdata'=>'V~O','label'=>'Time Zone','datatype'=>'picklist'));
+                'time_zone'    => array('name' => 'time_zone', 'typeofdata'=>'V~O','label'=>'Time Zone','datatype'=>'picklist'));
 
         $fieldsList = array();
         foreach($fields as $fieldName => $fieldInfo) {
@@ -62,31 +51,25 @@ class Settings_MailConverter_Module_Model extends Settings_Vtiger_Module_Model {
         return $fieldsList;
 	}
 
-    
-    public function getRuleFields(){
-        return $ruleFields = array(
-            'matchusing' => array('name' => 'matchusing', 'label' => 'LBL_MATCH', 'datatype' => 'radio'),
+	/**
+	 * Function to get the field of setup Rules
+	 *  @return <Array> List of setup rule fields
+	 */
+
+	public function getSetupRuleFiels() {
+		$ruleFields = array(
 			'fromaddress' => array('name' => 'fromaddress', 'label' => 'LBL_FROM', 'datatype' => 'email'),
 			'toaddress' => array('name' => 'toaddress', 'label' => 'LBL_TO', 'datatype' => 'email'),
 			'cc' => array('name' => 'cc', 'label' => 'LBL_CC', 'datatype' => 'email'),
 			'bcc' => array('name' => 'bcc', 'label' => 'LBL_BCC', 'datatype' => 'email'),
 			'subject' => array('name' => 'subject', 'label' => 'LBL_SUBJECT', 'datatype' => 'picklist'),
 			'body' => array('name' => 'body', 'label' => 'LBL_BODY', 'datatype' => 'picklist'),
+			'matchusing' => array('name' => 'matchusing', 'label' => 'LBL_MATCH', 'datatype' => 'radio'),
+			'action' => array('name' => 'action', 'label' => 'LBL_ACTION', 'datatype' => 'picklist')
 		);
-    }
-    
-	/**
-	 * Function to get the field of setup Rules
-	 *  @return <Array> List of setup rule fields
-	 */
-
-	public function getSetupRuleFiels() {
-        $moduleName = $this->name;
-		$ruleFields = $this->getRuleFields();
 		$ruleFieldsList = array();
 		foreach($ruleFields as $fieldName => $fieldInfo) {
-            $modelClassName = Vtiger_Loader::getComponentClassName('Model', 'RuleField', 'Settings:'.$moduleName);
-            $fieldModel = new $modelClassName();
+            $fieldModel = new Settings_MailConverter_RuleField_Model();
             foreach($fieldInfo as $key=>$value) {
                 $fieldModel->set($key, $value);
             }
@@ -100,7 +83,7 @@ class Settings_MailConverter_Module_Model extends Settings_Vtiger_Module_Model {
 	 * @return <String> Url
 	 */
 	public function getDefaultUrl() {
-		return 'index.php?module=' . $this->getName() . '&parent=' . $this->getParentName() . '&view=List';
+		return 'index.php?module='.$this->getName().'&parent='.$this->getParentName().'&view=List';
 	}
 
 	public function isPagingSupported() {
@@ -109,7 +92,7 @@ class Settings_MailConverter_Module_Model extends Settings_Vtiger_Module_Model {
 
 	public function MailBoxExists() {
 		$db = PearDatabase::getInstance();
-		$result = $db->pquery("SELECT COUNT(*) AS count FROM $this->baseTable", array());
+		$result = $db->pquery("SELECT COUNT(*) AS count FROM vtiger_mailscanner", array());
 		$response = $db->query_result($result, 0, 'count');
 		if ($response == 0)
 			return false;
@@ -118,7 +101,7 @@ class Settings_MailConverter_Module_Model extends Settings_Vtiger_Module_Model {
 
 	public function getDefaultId() {
 		$db = PearDatabase::getInstance();
-		$result = $db->pquery("SELECT MIN(scannerid) AS id FROM $this->baseTable", array());
+		$result = $db->pquery("SELECT MIN(scannerid) AS id FROM vtiger_mailscanner", array());
 		$id = $db->query_result($result, 0, 'id');
 		return $id;
 	}
@@ -126,7 +109,7 @@ class Settings_MailConverter_Module_Model extends Settings_Vtiger_Module_Model {
 	public function getMailboxes() {
 		$mailBox = array();
 		$db = PearDatabase::getInstance();
-		$result = $db->pquery("SELECT scannerid, scannername FROM $this->baseTable", array());
+		$result = $db->pquery("SELECT scannerid, scannername FROM vtiger_mailscanner", array());
 		$numOfRows = $db->num_rows($result);
 		for ($i = 0; $i < $numOfRows; $i++) {
 			$mailBox[$i]['scannerid'] = $db->query_result($result, $i, 'scannerid');
@@ -138,10 +121,10 @@ class Settings_MailConverter_Module_Model extends Settings_Vtiger_Module_Model {
 	public function getScannedFolders($id) {
 		$folders = array();
 		$db = PearDatabase::getInstance();
-		$result = $db->pquery("SELECT foldername FROM $this->scannedFoldersTable WHERE scannerid=? AND enabled=1", array($id));
+		$result = $db->pquery("SELECT foldername FROM vtiger_mailscanner_folders WHERE scannerid=? AND enabled=1", array($id));
 		$numOfRows = $db->num_rows($result);
 		for ($i = 0; $i < $numOfRows; $i++) {
-			$folders[$i] = decode_html($db->query_result($result, $i, 'foldername'));
+			$folders[$i] = $db->query_result($result, $i, 'foldername');
 		}
 		return $folders;
 	}
@@ -149,29 +132,29 @@ class Settings_MailConverter_Module_Model extends Settings_Vtiger_Module_Model {
 	public function getFolders($id) {
 		include_once 'modules/Settings/MailConverter/handlers/MailScannerInfo.php';
 		include_once 'modules/Settings/MailConverter/handlers/MailBox.php';
-		$scannerName = $this->getScannerName($id);
+		$scannerName = Settings_MailConverter_Module_Model::getScannerName($id);
 		$scannerInfo = new Vtiger_MailScannerInfo($scannerName);
 		$mailBox = new Vtiger_MailBox($scannerInfo);
 		$isConnected = $mailBox->connect();
-        if($isConnected) {
-            $allFolders = $mailBox->getFolders();
-            $folders = array();
-            $selectedFolders = $this->getScannedFolders($id);
-            if(is_array($allFolders)) {
-                foreach ($allFolders as $a) {
-                    if (in_array($a, $selectedFolders)) {
-                            $folders[$a] = 'checked';
-                    } else {
-                            $folders[$a] = '';
-                    }
-                }
-                return $folders;
-            } else {
-                return $allFolders;
-            }
+                if($isConnected) {
+                        $allFolders = $mailBox->getFolders();
+                        $folders = array();
+                        $selectedFolders = Settings_MailConverter_Module_Model::getScannedFolders($id);
+                        if(is_array($allFolders)) {
+                                foreach ($allFolders as $a) {
+                                        if (in_array($a, $selectedFolders)) {
+                                                $folders[$a] = 'checked';
+                                        } else {
+                                                $folders[$a] = '';
+                                        }
+                                }
+                                return $folders;
+                        } else {
+                                return $allFolders;
+                        }
 
-        }
-        return false;
+                }
+                return false;
 	}
 
 	public function getScannerName($id) {
@@ -184,43 +167,13 @@ class Settings_MailConverter_Module_Model extends Settings_Vtiger_Module_Model {
 	public function updateFolders($scannerId, $folders) {
 		include_once 'modules/Settings/MailConverter/handlers/MailScannerInfo.php';
 		$db = PearDatabase::getInstance();
-        $moduleModel = Settings_Vtiger_Module_Model::getInstance('Settings:MailConverter');
-		$scannerName = $moduleModel->getScannerName($scannerId);
+		$scannerName = Settings_MailConverter_Module_Model::getScannerName($scannerId);
 		$scannerInfo = new Vtiger_MailScannerInfo($scannerName);
-        if($scannerInfo->scanfrom == 'ALL') {
-            // If MailServer timezone is -12:00 or near then last scan time should be 02-Jan-1970.
-            // If we use 01-Jan-1970 imap_search will not give any result
-            $lastScan = "02-Jan-1970";
-        } else {
-            $lastScan = $scannerInfo->dateBasedOnMailServerTimezone('d-M-Y');
-        }
-        
-        $result = $db->pquery("SELECT foldername FROM $this->scannedFoldersTable WHERE scannerid = ?", array($scannerId));
-        $oldFolders = array();
-        $folderCount = $db->num_rows($result);
-        for($i = 0; $i < $folderCount; $i++) {
-            $oldFolders[] = decode_html($db->query_result($result, $i, 'foldername'));
-        }
-        
-        $foldersToDelete = array_diff($oldFolders, $folders);
-        $foldersToAdd = array_diff($folders, $oldFolders);
-        
-		foreach ($foldersToAdd as $folder) {
-			$db->pquery("INSERT INTO $this->scannedFoldersTable VALUES(?,?,?,?,?,?)", array('', $scannerId, $folder, $lastScan, '0', '1'));
+		$lastScan = $scannerInfo->dateBasedOnMailServerTimezone('d-M-Y');
+		$db->pquery("DELETE FROM vtiger_mailscanner_folders WHERE scannerid=?", array($scannerId));
+		foreach ($folders as $folder) {
+			$db->pquery("INSERT INTO vtiger_mailscanner_folders VALUES(?,?,?,?,?,?)", array('', $scannerId, $folder, $lastScan, '0', '1'));
 		}
-        foreach($foldersToDelete as $folder) {
-            $db->pquery("DELETE FROM $this->scannedFoldersTable WHERE scannerid = ? AND foldername = ?", array($scannerId, $folder));
-        }
 	}
 
-    function getMaxScannerId(){
-        $db = PearDatabase::getInstance();
-        $result = $db->pquery('SELECT seq FROM vtiger_scanner_seq',array());
-        return $db->query_result($result,0,'seq');
-    }
-    
-    function updateMaxScannerId($seq){
-        $db = PearDatabase::getInstance();
-        $db->pquery('UPDATE vtiger_scanner_seq SET seq=?',array($seq+1));
-    }
 }
diff --git a/modules/Settings/MailConverter/models/Record.php b/modules/Settings/MailConverter/models/Record.php
index 6b5004c72be35c989b4c4404ca4e29840af57bdc..43ec6f8d4021c92d3df94dca20bd65437eac4335 100644
--- a/modules/Settings/MailConverter/models/Record.php
+++ b/modules/Settings/MailConverter/models/Record.php
@@ -10,16 +10,6 @@
 
 class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
 
-    //Overridden table names and fields
-    var $baseTable = 'vtiger_mailscanner';
-    var $baseTableIndex = 'scannerid';
-    var $fieldName = 'scannername';
-    var $scannedFoldersTable = 'vtiger_mailscanner_folders';
-    var $scannerRulesTable = 'vtiger_mailscanner_rules';
-    var $scannerIdsTable = 'vtiger_message_ids';
-    
-    
-    
 	/**
 	 * Function to get Id of this record instance
 	 * @return <Integer> Id
@@ -60,7 +50,7 @@ class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
 	 */
 	public function hasRules() {
 		$db = PearDatabase::getInstance();
-		$result = $db->pquery("SELECT 1 FROM ".$this->scannerRulesTable." WHERE scannerid = ?", array($this->getId()));
+		$result = $db->pquery('SELECT 1 FROM vtiger_mailscanner_rules WHERE scannerid = ?', array($this->getId()));
 		if ($db->num_rows($result)) {
 			return true;
 		}
@@ -109,7 +99,8 @@ class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
 
 	public function  getCreateRuleRecordUrl() {
 		$moduleModel = $this->getModule();
-		return 'index.php?module='. $moduleModel->getName() .'&parent=Settings&scannerId='.$this->getId().'&view=EditRule&mode=step1';
+		$url = 'index.php?module='. $moduleModel->getName() .'&parent=Settings&scannerId='.$this->getId().'&view=EditRule';
+		return 'javascript:Settings_MailConverter_Index_Js.triggerRuleEdit("'.$url.'")';
 	}
 
 	/**
@@ -181,7 +172,7 @@ class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
 	 */
 	public function delete() {
         vimport('~~modules/Settings/MailConverter/handlers/MailScannerInfo.php');
-        $scanner = new Vtiger_MailScannerInfo(trim(decode_html($this->getName())));
+        $scanner = new Vtiger_MailScannerInfo(trim($this->getName()));
 		$scanner->delete();
 	}
 
@@ -190,14 +181,6 @@ class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
 	 * @return <Boolean> true/false (Saved/Not Saved)
 	 */
 	public function save() {
-        if($this->isDulpicateScannerName()) {
-            $this->set('errorMsg', 'LBL_DUPLICATE_SCANNERNAME_ERROR');
-            return false;
-        }
-        if($this->isDulpicateUserName()) {
-            $this->set('errorMsg', 'LBL_DUPLICATE_USERNAME_ERROR');
-            return false;
-        }
         vimport('~~modules/Settings/MailConverter/handlers/MailScannerInfo.php');
 		$scannerLatestInfo = new Vtiger_MailScannerInfo(false, false);
 		$fieldsList = $this->getModule()->getFields();
@@ -208,7 +191,19 @@ class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
 		if (!empty($scannerId)) {
 			$scannerLatestInfo->scannerid = $this->getId();
 		}
+		//Checking Scanner Name
+		$scannerName = $this->getName();
+		if($scannerName && !validateAlphanumericInput($scannerName)) {
+			return false;
+		}
+
+		//Checking Server
+		$server = $this->get('server');
+		if($server && !validateServerName($server)) {
+			return false;
+		}
 
+		
 		$isConnected = true;
 		$scannerOldInfo = new Vtiger_MailScannerInfo($this->get('scannerOldName'));
 
@@ -233,9 +228,7 @@ class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
 				$rescanFolder = true;
 			}
 			$scannerOldInfo->updateAllFolderRescan($rescanFolder);
-		} else {
-            $this->set('errorMsg', $mailBox->_imaperror);
-        }
+		}
 		return $isConnected;
 	}
 
@@ -252,11 +245,8 @@ class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
 			/** Start the scanning. */
 			$scanner = new Vtiger_MailScanner($scannerInfo);
 			$status = $scanner->performScanNow();
-            if(empty($status))
-                $this->set('errorMsg', 'LBL_NO_RULES');
 			return $status;
 		}
-        $this->set('errorMsg', 'LBL_MAIL_SCANNER_INACTIVE');
 		return false;
 	}
 
@@ -295,7 +285,7 @@ class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
 		$db = PearDatabase::getInstance();
 		$foldersData = $this->get('foldersData');
 
-		$updateQuery = "UPDATE $this->scannedFoldersTable SET enabled = CASE folderid ";
+		$updateQuery = "UPDATE vtiger_mailscanner_folders SET enabled = CASE folderid ";
 		foreach ($foldersData as $folderId => $enabled) {
 			$updateQuery .= " WHEN $folderId THEN $enabled ";
 		}
@@ -311,7 +301,7 @@ class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
 	public function updateSequence($sequencesList) {
 		$db = PearDatabase::getInstance();
 
-		$updateQuery = "UPDATE $this->scannerRulesTable SET sequence = CASE";
+		$updateQuery = "UPDATE vtiger_mailscanner_rules SET sequence = CASE";
 		foreach ($sequencesList as $sequence => $ruleId) {
 			$updateQuery .= " WHEN ruleid = $ruleId THEN $sequence ";
 		}
@@ -338,12 +328,11 @@ class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
 	 */
 	public static function getInstanceById($recordId) {
 		$db = PearDatabase::getInstance();
-		$result = $db->pquery("SELECT * FROM vtiger_mailscanner WHERE scannerid = ", array($recordId));
+		$result = $db->pquery('SELECT * FROM vtiger_mailscanner WHERE scannerid = ', array($recordId));
 		if ($db->num_rows($result)) {
 			$recordModel = self::getCleanInstance();
 			$recordModel->setData($db->query_result_rowdata($result));
-                        $recordModel->set('servertype', $recordModel->getServerType($recordModel->get('server')));
-                        return $recordModel->set('password', $recordModel->__crypt($recordModel->get('password'),false));
+            return $recordModel->set('password', $recordModel->__crypt($recordModel->get('password'),false));
 		}
 		return false;
 	}
@@ -370,7 +359,9 @@ class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
 
 	public static function getCount() {
 		$db = PearDatabase::getInstance();
-		$result = $db->pquery("SELECT 1 FROM vtiger_mailscanner", array());
+		$moduleModel = Settings_Vtiger_Module_Model::getInstance('Settings:MailConverter');
+
+		$result = $db->pquery('SELECT 1 FROM vtiger_mailscanner', array());
 		$numOfRows = $db->num_rows($result);
 		return $numOfRows;
 	}
@@ -404,68 +395,4 @@ class Settings_MailConverter_Record_Model extends Settings_Vtiger_Record_Model {
         }
         return $value;
     }
-    
-    function getLastScanTime() {
-        $lastScan = $this->get('last_scan');
-        if(!empty($lastScan) && $lastScan != '0000-00-00 00:00:00') {
-            $dateTime = new DateTimeField($lastScan);
-            return $dateTime->getDisplayDate().' '.Vtiger_Time_UIType::getDisplayValue($dateTime->getDisplayTime());
-        } else {
-            return '';
-        }
-    }
-    
-    function getServerType($serverName) {
-        $defaultServers = array('imap.gmail.com', 'imap.mail.yahoo.com', 'mail.messagingengine.com');
-        if(!in_array($serverName, $defaultServers)) {
-            return 'other';
-        } else {
-            return $serverName;
-        }
-    }
-    
-    function isDulpicateUserName() {
-        $server = $this->get('server');
-        $userName = $this->get('username');
-        $scannerId = $this->getId();
-        $db = PearDatabase::getInstance();
-        $userNameParts = explode('@', $userName);
-        $query = "SELECT server, username FROM $this->baseTable WHERE username LIKE ?";
-        $params = array('%'.$userNameParts[0].'%');
-        if(!empty($scannerId)) {
-            $query .= " AND scannerid <> ?";
-            array_push($params, $scannerId);
-        }
-        $result = $db->pquery($query, $params);
-        $count = $db->num_rows($result);
-        if($count > 0) {
-            for($i = 0; $i < $count; $i++) {
-                $storedServer = $db->query_result($result, $i, 'server');
-                $storedUsername = $db->query_result($result, $i, 'username');
-                $storedUsernameParts = explode('@', $storedUsername);
-                if(($userName == $storedUsername) || ($userNameParts[0] == $storedUsernameParts[0] && $server == $storedServer)) {
-                    return true;
-                }
-            }
-        }
-        
-        return false;
-    }
-    
-    function isDulpicateScannerName() {
-        $db = PearDatabase::getInstance();
-        $scannerId = $this->getId();
-        $query = "SELECT 1 FROM $this->baseTable WHERE scannername = ?";
-        $params = array($this->getName());
-        if(!empty($scannerId)) {
-            $query .= " AND scannerid <> ?";
-            array_push($params, $scannerId);
-        }
-        $result = $db->pquery($query, $params);
-        if($db->num_rows($result) > 0) {
-            return true;
-        } else {
-            return false;
-        }
-    }
 }
\ No newline at end of file
diff --git a/modules/Settings/MailConverter/models/RuleField.php b/modules/Settings/MailConverter/models/RuleField.php
index cd730281a1f5abbebc1f97785b7808435d1fb04d..d8d95d03edcf25a5ba39738f9dca86458d859164 100644
--- a/modules/Settings/MailConverter/models/RuleField.php
+++ b/modules/Settings/MailConverter/models/RuleField.php
@@ -1,58 +1,49 @@
-<?php
-
-/*+**********************************************************************************
- * The contents of this file are subject to the vtiger CRM Public License Version 1.1
- * ("License"); You may not use this file except in compliance with the License
- * The Original Code is:  vtiger CRM Open Source
- * The Initial Developer of the Original Code is vtiger.
- * Portions created by vtiger are Copyright (C) vtiger.
- * All Rights Reserved.
- ************************************************************************************/
-
-class Settings_MailConverter_RuleField_Model extends Vtiger_Field_Model {
-    
-	public function getFieldDataType() {
-        return $this->get('datatype');
-    }
-	
-	public function getPickListValues($fieldName = false) {
-        if(!$fieldName)
-            $fieldName = $this->getName();
-        $pickListValues = array();
-        if($fieldName == 'subject') {
-            $optionList = array('Contains', 'Not Contains', 'Equals', 'Not Equals', 'Has Ticket Number', 'Begins With', 'Ends With', 'Regex');
-            foreach($optionList as $option) {
-                $pickListValues[$option] = vtranslate($option, 'Settings::MailConverter');
-            }
-        }else if ($fieldName == 'body') {
-            $optionList = array('Contains', 'Not Contains', 'Equals', 'Not Equals', 'Begins With', 'Ends With');
-            foreach($optionList as $option) {
-				$pickListValues[$option] = vtranslate($option, 'Settings::MailConverter');
-			}
-		} else if ($fieldName == 'action') {
-			$optionList = array(
-				'HelpDesk' => array('CREATE_HelpDesk_FROM', 'LINK_HelpDesk_FROM', 'LINK_HelpDesk_TO', 'CREATE_HelpDeskNoContact_FROM', 'UPDATE_HelpDesk_SUBJECT'), 
-				'Leads' => array('CREATE_Leads_SUBJECT', 'LINK_Leads_FROM', 'LINK_Leads_TO'),
-				'Contacts' => array('CREATE_Contacts_SUBJECT', 'LINK_Contacts_FROM', 'LINK_Contacts_TO'),
-				'Accounts' => array('CREATE_Accounts_SUBJECT', 'LINK_Accounts_FROM', 'LINK_Accounts_TO'), 
-				'Potentials' => array('CREATE_Potentials_SUBJECT', 'LINK_Potentials_FROM', 'LINK_Potentials_TO', 'CREATE_PotentialsNoContact_SUBJECT'), 
-			);
-			foreach ($optionList as $module => $option) {
-				foreach ($option as $value) {
-					$pickListValues[$value] = vtranslate($value, 'Settings::MailConverter');
-				}
-            }
-		}
-        return $pickListValues;
-    }
-	
-	public function getRadioOptions($qualifiedModule = 'Settings::MailConverter') {
-        $fieldName = $this->getName();
-        if($fieldName == 'matchusing') {
-            $options['AND'] = vtranslate('LBL_ALL_CONDITIONS',$qualifiedModule);
-            $options['OR'] = vtranslate('LBL_ANY_CONDITIONS',$qualifiedModule);
-        }
-        return $options;
-    }
-}	
-?>
+<?php
+
+/*+**********************************************************************************
+ * The contents of this file are subject to the vtiger CRM Public License Version 1.1
+ * ("License"); You may not use this file except in compliance with the License
+ * The Original Code is:  vtiger CRM Open Source
+ * The Initial Developer of the Original Code is vtiger.
+ * Portions created by vtiger are Copyright (C) vtiger.
+ * All Rights Reserved.
+ ************************************************************************************/
+
+class Settings_MailConverter_RuleField_Model extends Vtiger_Field_Model {
+    
+	public function getFieldDataType() {
+        return $this->get('datatype');
+    }
+	
+	public function getPickListValues() {
+        $fieldName = $this->getName();
+        $pickListValues = array();
+        if($fieldName == 'subject') {
+            $optionList = array('Contains', 'Not Contains', 'Equals', 'Not Equals', 'Has Ticket Number', 'Begins With', 'Ends With', 'Regex');
+            foreach($optionList as $option) {
+                $pickListValues[$option] = vtranslate($option, 'Settings::MailConverter');
+            }
+        }else if ($fieldName == 'body') {
+            $optionList = array('Contains', 'Not Contains', 'Equals', 'Not Equals', 'Begins With', 'Ends With');
+            foreach($optionList as $option) {
+				$pickListValues[$option] = vtranslate($option, 'Settings::MailConverter');
+			}
+		} else if ($fieldName == 'action') {
+			$optionList = array('CREATE_HelpDesk_FROM', 'UPDATE_HelpDesk_SUBJECT', 'CREATE_Leads_SUBJECT', 'CREATE_Contacts_SUBJECT', 'CREATE_Accounts_SUBJECT', 'LINK_Contacts_FROM', 'LINK_Contacts_TO', 'LINK_Leads_FROM', 'LINK_Leads_TO', 'LINK_Accounts_FROM', 'LINK_Accounts_TO');
+			foreach ($optionList as $option) {
+				$pickListValues[$option] = vtranslate($option, 'Settings::MailConverter');
+            }
+		}
+        return $pickListValues;
+    }
+	
+	public function getRadioOptions() {
+        $fieldName = $this->getName();
+        if($fieldName == 'matchusing') {
+            $options['AND'] = vtranslate('LBL_ALL_CONDITIONS','Settings::MailConverter');
+            $options['OR'] = vtranslate('LBL_ANY_CONDITIONS','Settings::MailConverter');
+        }
+        return $options;
+    }
+}	
+?>
diff --git a/modules/Settings/MailConverter/models/RuleRecord.php b/modules/Settings/MailConverter/models/RuleRecord.php
index 609ccb36b9e0d673d7fa2a3e0cf38bda9490fe23..85ff9788e69ccf572b87e035ff881dbef6828da2 100644
--- a/modules/Settings/MailConverter/models/RuleRecord.php
+++ b/modules/Settings/MailConverter/models/RuleRecord.php
@@ -12,9 +12,11 @@ vimport('~~modules/Settings/MailConverter/handlers/MailScannerAction.php');
 vimport('~~modules/Settings/MailConverter/handlers/MailScannerRule.php');
 
 class Settings_MailConverter_RuleRecord_Model extends Settings_Vtiger_Record_Model {
-    
-    var $_bodyruleTable = 'vtiger_mailscanner_bodyrule';
-    
+
+	var $assignedTo = false;
+	var $cc = false;
+	var $bcc = false;
+
 	/**
 	 * Function to get Id of this record instance
 	 * @return <Integer> Id
@@ -35,7 +37,7 @@ class Settings_MailConverter_RuleRecord_Model extends Settings_Vtiger_Record_Mod
 	 * @return <Array> List of fields
 	 */
 	public function getFields() {
-		return array('fromaddress', 'toaddress', 'cc', 'bcc', 'subjectop', 'subject', 'bodyop', 'body', 'matchusing', 'assigned_to');
+		return array('fromaddress', 'toaddress', 'cc', 'bcc', 'subjectop', 'subject', 'bodyop', 'body', 'matchusing');
 	}
 
 	/**
@@ -59,8 +61,8 @@ class Settings_MailConverter_RuleRecord_Model extends Settings_Vtiger_Record_Mod
 	 * @return <String> Url
 	 */
 	public function getEditViewUrl() {
-		$url = $this->getDefaultUrl(). '&view=EditRule&mode=step1';
-		return $url;
+		$url = $this->getDefaultUrl(). '&view=EditRule';
+		return 'javascript:Settings_MailConverter_Index_Js.triggerRuleEdit("'.$url.'")';
 	}
 
 	/**
@@ -134,6 +136,9 @@ class Settings_MailConverter_RuleRecord_Model extends Settings_Vtiger_Record_Mod
 		$ruleModel = new Vtiger_MailScannerRule($recordId);
 		$fieldsList = $this->getFields();
 		$ruleModel->scannerid = $this->get('scannerid');
+		$ruleModel->assigned_to = $this->assignedTo;
+		$ruleModel->cc = $this->cc;
+		$ruleModel->bcc = $this->bcc;
 		foreach ($fieldsList as $fieldName) {
 			$ruleModel->$fieldName = $this->get($fieldName);
 		}
@@ -243,10 +248,7 @@ class Settings_MailConverter_RuleRecord_Model extends Settings_Vtiger_Record_Mod
 	 * @return <Array> List of default actions
 	 */
 	public static function getDefaultActions() {
-		return array('CREATE_HelpDesk_FROM', 'CREATE_HelpDeskNoContact_FROM', 'UPDATE_HelpDesk_SUBJECT', 'CREATE_Leads_SUBJECT',
-            'CREATE_Contacts_SUBJECT', 'CREATE_Accounts_SUBJECT', 'CREATE_Potentials_SUBJECT', 'CREATE_PotentialsNoContact_SUBJECT', 'LINK_Contacts_FROM', 'LINK_Contacts_TO',
-            'LINK_Leads_FROM', 'LINK_Leads_TO', 'LINK_Accounts_FROM', 'LINK_Accounts_TO', 'LINK_Potentials_FROM', 'LINK_Potentials_TO',
-            'LINK_HelpDesk_FROM', 'LINK_HelpDesk_TO');
+		return array('CREATE_HelpDesk_FROM', 'UPDATE_HelpDesk_SUBJECT', 'LINK_Contacts_FROM', 'LINK_Contacts_TO', 'LINK_Leads_FROM', 'LINK_Leads_TO', 'LINK_Accounts_FROM', 'LINK_Accounts_TO');
 	}
 
 	public function getAssignedTo($scannerId, $ruleId) {
@@ -264,19 +266,4 @@ class Settings_MailConverter_RuleRecord_Model extends Settings_Vtiger_Record_Mod
 		}
 		return array($id, $assignedUserName);
 	}
-    
-    public function bodyRuleExists() {
-        $ruleId = $this->getId();
-        $scannerId = $this->getScannerId();
-        if(empty($ruleId) || empty($scannerId)) {
-            return false;
-        }
-        $db = PearDatabase::getInstance();
-        $result = $db->pquery("SELECT 1 FROM $this->_bodyruleTable WHERE scannerid = ? AND ruleid = ?", array($scannerId, $ruleId));
-        $count = $db->num_rows($result);
-        if($count > 0)
-            return true;
-        else
-            return false;
-    }
-}
+}
\ No newline at end of file
diff --git a/modules/Settings/MailConverter/views/Edit.php b/modules/Settings/MailConverter/views/Edit.php
index 6f1bfb9ece036bd72d0f2ba9a31c13b38367aa67..ab2b21761f198f2a77d6a0a78b891eb1a8922ec5 100644
--- a/modules/Settings/MailConverter/views/Edit.php
+++ b/modules/Settings/MailConverter/views/Edit.php
@@ -14,79 +14,102 @@ class Settings_MailConverter_Edit_View extends Settings_Vtiger_Index_View {
 		parent::__construct();
 		$this->exposeMethod('step1');
 		$this->exposeMethod('step2');
-    }
-    
-    public function preProcess(Vtiger_Request $request) {
+		$this->exposeMethod('step3');
+	}
+
+	public function process(Vtiger_Request $request) {
+		$mode = $request->get('mode');
+		if (!empty($mode)) {
+			$this->invokeExposedMethod($mode, $request);
+			return;
+		}
+	}
+
+	public function preProcess(Vtiger_Request $request) {
 		parent::preProcess($request);
 		$recordId = $request->get('record');
 		$mode = $request->get('mode');
 		if (!$mode)
-		    $mode = "step1";
+			$mode = "step1";
 		$qualifiedModuleName = $request->getModule(false);
 		$moduleName = $request->getModule();
-        
-        $modelClassName = Vtiger_Loader::getComponentClassName('Model', 'Record', $qualifiedModuleName);
+
 		if ($recordId) {
-            $recordModel =  call_user_func_array(array($modelClassName,'getInstanceById'),array($recordId));
+			$recordModel = Settings_MailConverter_Record_Model::getInstanceById($recordId);
 		} else {
-            $recordModel = call_user_func_array(array($modelClassName,'getCleanInstance'),array());
+			$recordModel = Settings_MailConverter_Record_Model::getCleanInstance();
 		}
 		$viewer = $this->getViewer($request);
-	
-		if ($recordId)
-		    $viewer->assign('RECORD_ID', $recordId);
+
+		if ($recordId) {
+			$viewer->assign('RECORD_ID', $recordId);
+		}
 		$viewer->assign('CREATE', $request->get('create'));
 		$viewer->assign('RECORD_MODEL', $recordModel);
 		$viewer->assign('MODULE_MODEL', $recordModel->getModule());
 		$viewer->assign('STEP', $mode);
 		$viewer->assign('MODULE_NAME', $moduleName);
 		$viewer->assign('QUALIFIED_MODULE', $qualifiedModuleName);
-	
 		$viewer->view('EditHeader.tpl', $qualifiedModuleName);
-    }
+	}
 
-	public function process(Vtiger_Request $request) {
-		$mode = $request->get('mode');
-		if (!empty($mode)) {
-		    $this->invokeExposedMethod($mode, $request);
-		    return;
-		}
-    }
-    
-    public function step1(Vtiger_Request $request) {
+	public function step1(Vtiger_Request $request) {
 		$qualifiedModuleName = $request->getModule(false);
 		$viewer = $this->getViewer($request);
-	
 		$viewer->view('Step1.tpl', $qualifiedModuleName);
 	}
-	
+
 	public function step2(Vtiger_Request $request) {
 		$recordId = $request->get('record');
 		$qualifiedModuleName = $request->getModule(false);
-        $moduleModel = Settings_Vtiger_Module_Model::getInstance($qualifiedModuleName);
-        $folders = $moduleModel->getFolders($recordId);
+		$folders = Settings_MailConverter_Module_Model::getFolders($recordId);
 		$viewer = $this->getViewer($request);
-        if(is_array($folders))
-            $viewer->assign('FOLDERS', $folders);
-        else if($folders)
-            $viewer->assign('IMAP_ERROR', $folders);
-        else
-            $viewer->assign('CONNECTION_ERROR', true);
-	
+		$folders = array('aasdasdsad','bsadasdsad','casadsad','dsdasdsa', 'eadasdsd', 'fasdsasd');
+		if (is_array($folders)) {
+			$viewer->assign('FOLDERS', array_flip($folders));
+		} else if ($folders) {
+			$viewer->assign('IMAP_ERROR', $folders);
+		} else {
+			$viewer->assign('CONNECTION_ERROR', true);
+		}
 		$viewer->view('Step2.tpl', $qualifiedModuleName);
-    }
+	}
+
+	public function step3(Vtiger_Request $request) {
+		$scannerId = $request->get('record');
+		$moduleName = $request->getModule();
+		$recordModel = Settings_MailConverter_RuleRecord_Model::getCleanInstance($scannerId);
+		$qualifiedModuleName = $request->getModule(false);
+		global $current_user;
+		$currentUserId = $current_user->id;
+		$viewer = $this->getViewer($request);
+
+		$viewer->assign('RECORD_MODEL', $recordModel);
+		$viewer->assign('DEFAULT_MATCH', "AND");
+		$viewer->assign('MODULE_MODEL', new Settings_MailConverter_Module_Model());
 
-    public function getHeaderScripts(Vtiger_Request $request) {
+		$viewer->assign('SCANNER_ID', $scannerId);
+		$viewer->assign('SCANNER_MODEL', Settings_MailConverter_Record_Model::getInstanceById($scannerId));
+
+		$viewer->assign('DEFAULT_OPTIONS', Settings_MailConverter_RuleRecord_Model::getDefaultConditions());
+		$viewer->assign('DEFAULT_ACTIONS', Settings_MailConverter_RuleRecord_Model::getDefaultActions());
+		$viewer->assign('USER_MODEL', Users_Record_Model::getCurrentUserModel());
+		$viewer->assign('MODULE_NAME', $moduleName);
+		$viewer->assign('ASSIGNED_USER', $currentUserId);
+
+		$viewer->view('Step3.tpl', $qualifiedModuleName);
+	}
+
+	public function getHeaderScripts(Vtiger_Request $request) {
 		$headerScriptInstances = parent::getHeaderScripts($request);
-        $module = $request->getModule();
-	
+
 		$jsFileNames = array(
-		    "modules.Settings.$module.resources.Edit"
+			'modules.Settings.MailConverter.resources.Edit'
 		);
-	
+
 		$jsScriptInstances = $this->checkAndConvertJsScripts($jsFileNames);
 		$headerScriptInstances = array_merge($headerScriptInstances, $jsScriptInstances);
 		return $headerScriptInstances;
-    }
+	}
 
-}
\ No newline at end of file
+}
diff --git a/modules/Settings/MailConverter/views/EditRule.php b/modules/Settings/MailConverter/views/EditRule.php
index 25862a410a92b051bc1153c4afca54edebd96749..a459ec9f787bb5c623e5a321158a6ca027e64c92 100644
--- a/modules/Settings/MailConverter/views/EditRule.php
+++ b/modules/Settings/MailConverter/views/EditRule.php
@@ -8,13 +8,7 @@
  * All Rights Reserved.
  *************************************************************************************/
 
-class Settings_MailConverter_EditRule_View extends Settings_Vtiger_Index_View {
-    
-    function __construct() {
-		parent::__construct();
-		$this->exposeMethod('step1');
-		$this->exposeMethod('step2');
-    }
+class Settings_MailConverter_EditRule_View extends Settings_Vtiger_IndexAjax_View {
 
 	public function checkPermission(Vtiger_Request $request) {
 		parent::checkPermission($request);
@@ -24,98 +18,38 @@ class Settings_MailConverter_EditRule_View extends Settings_Vtiger_Index_View {
 			throw new AppException(vtranslate('LBL_PERMISSION_DENIED', $request->getModule(false)));
 		}
 	}
-    
-    public function preProcess(Vtiger_Request $request) {
-		parent::preProcess($request);
+
+	public function process(Vtiger_Request $request) {
 		$recordId = $request->get('record');
-        $scannerId = $request->get('scannerId');
+		$scannerId = $request->get('scannerId');
 		$qualifiedModuleName = $request->getModule(false);
-        $moduleName = $request->getModule();
-		$mode = $request->get('mode');
-        $ruleRecordModel = Vtiger_Loader::getComponentClassName('Model', 'RuleRecord', $qualifiedModuleName);
-        $ruleRecordModel = new $ruleRecordModel();
-        $viewer = $this->getViewer($request);
-		if (empty($mode)) {
-		    $mode = "step1";
-        }
+		$moduleName = $request->getModule();
+
 		if ($recordId) {
-           $ruleRecordModel = call_user_func_array(array($ruleRecordModel,'getInstanceById'),array($recordId));
+			$recordModel = Settings_MailConverter_RuleRecord_Model::getInstanceById($recordId);
 		} else {
-            $ruleRecordModel = call_user_func_array(array($ruleRecordModel,'getCleanInstance'),array($scannerId));
+			$recordModel = Settings_MailConverter_RuleRecord_Model::getCleanInstance($scannerId);
 		}
-        $moduleModel =  Settings_Vtiger_Module_Model::getInstance($qualifiedModuleName);
-        $recordModel = Settings_Vtiger_Record_Model::getInstance($qualifiedModuleName);
-        $ruleExists = $ruleRecordModel->get('ruleid');
-        
+	
+		$assignedTo = Settings_MailConverter_RuleRecord_Model::getAssignedTo($scannerId, $recordId);
+		$viewer = $this->getViewer($request);
+
 		$viewer->assign('RECORD_ID', $recordId);
-        $viewer->assign('RULE_EXISTS', $ruleExists);
-		$viewer->assign('RECORD_MODEL', $ruleRecordModel);
-		$viewer->assign('MODULE_MODEL',new $moduleModel());
+		$viewer->assign('RECORD_MODEL', $recordModel);
+		$viewer->assign('MODULE_MODEL',new Settings_MailConverter_Module_Model());
+
 		$viewer->assign('SCANNER_ID', $scannerId);
-		$viewer->assign('SCANNER_MODEL', call_user_func_array(array($recordModel,'getInstanceById'),array($scannerId)));
-		$viewer->assign('DEFAULT_OPTIONS', call_user_func_array(array($ruleRecordModel,'getDefaultConditions'),array()));
-		$viewer->assign('DEFAULT_ACTIONS',call_user_func_array(array($ruleRecordModel,'getDefaultActions'),array()));
+		$viewer->assign('SCANNER_MODEL', Settings_MailConverter_Record_Model::getInstanceById($scannerId));
+		
+		
+		$viewer->assign('DEFAULT_OPTIONS', Settings_MailConverter_RuleRecord_Model::getDefaultConditions());
+		$viewer->assign('DEFAULT_ACTIONS', Settings_MailConverter_RuleRecord_Model::getDefaultActions());
+
+		$viewer->assign('MODULE_NAME', $moduleName);
 		$viewer->assign('QUALIFIED_MODULE', $qualifiedModuleName);
 		$viewer->assign('USER_MODEL', Users_Record_Model::getCurrentUserModel());
-		$viewer->assign('STEP', $mode);
-		$viewer->assign('MODULE_NAME', $moduleName);
-		$viewer->view('EditRuleHeader.tpl', $qualifiedModuleName);
-    }
-
-    public function process(Vtiger_Request $request) {
-		$mode = $request->get('mode');
-		if (!empty($mode)) {
-		    $this->invokeExposedMethod($mode, $request);
-		    return;
-		}
-    }
-    
-	public function step1(Vtiger_Request $request) {
-		$qualifiedModuleName = $request->getModule(false);
-		$viewer = $this->getViewer($request);
-		$viewer->view('RuleStep1.tpl', $qualifiedModuleName);
-	}
-    
-    public function step2(Vtiger_Request $request) {
-        $recordId = $request->get('record');
-		$scannerId = $request->get('scannerId');
-        $qualifiedModuleName = $request->getModule(false);
-        
-        $ruleRecordModelClassName = Vtiger_Loader::getComponentClassName('Model', 'RuleRecord', $qualifiedModuleName);
-        $ruleRecordModel  = new $ruleRecordModelClassName();
-        $assignedTo = $ruleRecordModel->getAssignedTo($scannerId, $recordId);
-        
-        
-        $bodyRule = Settings_MailConverter_BodyRule_Model::getCleanInstance($qualifiedModuleName);
-        $bodyRule->set('scannerid', $scannerId);
-        $bodyRule->set('ruleid', $recordId);
-        $bodyRuleExists = $bodyRule->bodyRuleExists();
-        if(!empty($recordId) && $bodyRuleExists) {
-            $delimiter = $bodyRule->getDelimiter();
-            $body = $bodyRule->getBody();
-            $mappingData = $bodyRule->getMapping();
-                           
-            $recordModel = call_user_func_array(array($ruleRecordModel,'getInstanceById'),array($recordId));
-            $action = $recordModel->get('action');
-            
-            $moduleFields = $bodyRule->getModuleFields($action);
-            $bodyFields = $bodyRule->parseBody($body, $delimiter);
-            $mappedBodyFields = array_keys($mappingData);
-            $bodyFields = array_unique(array_merge($bodyFields, $mappedBodyFields));
-        }
-        
-        $viewer = $this->getViewer($request);
 		$viewer->assign('ASSIGNED_USER', $assignedTo[0]);
-        $viewer->assign('DATA', $request->getAll());
-        if(!empty($recordId) && $bodyRuleExists) {
-            $viewer->assign('BODY_RULE_EXISTS', $bodyRuleExists);
-            $viewer->assign('DELIMITER', $delimiter);
-            $viewer->assign('BODY', $body);
-            $viewer->assign('MODULE_FIELDS', $moduleFields);
-            $viewer->assign('BODY_FIELDS', $bodyFields);
-            $viewer->assign('MAPPING', $mappingData);
-        }
-        $viewer->view('RuleStep2.tpl', $qualifiedModuleName);
-        
-    }
+	
+		$viewer->view('RuleEditView.tpl', $qualifiedModuleName);
+	}
 }
\ No newline at end of file
diff --git a/modules/Settings/MailConverter/views/List.php b/modules/Settings/MailConverter/views/List.php
index 6c3f48456c8bac141f6df3744593d8c020921cf9..fd2d9685efefc66526586f221363881f90b29ad0 100644
--- a/modules/Settings/MailConverter/views/List.php
+++ b/modules/Settings/MailConverter/views/List.php
@@ -13,40 +13,32 @@ class Settings_MailConverter_List_View extends Settings_Vtiger_Index_View {
 	public function process(Vtiger_Request $request) {
 		$moduleName = $request->getModule();
 		$scannerId = $request->get('record');
-        $qualifiedModuleName = $request->getModule(false);
-		$moduleModel = Settings_Vtiger_Module_Model::getInstance($qualifiedModuleName);
-        $recordModel = Settings_MailConverter_Record_Model::getCleanInstance();
-        
-        $mailroomRecordModel = Settings_Mailroom_Record_Model::getCleanInstance();
-        $mailroomListViewURL = $mailroomRecordModel->getListViewUrl();
-        
-		if ($scannerId == '')
-		    $scannerId = $moduleModel->getDefaultId();
-        
+		if ($scannerId == '') {
+			$scannerId = Settings_MailConverter_Module_Model::getDefaultId();
+		}
+		$qualifiedModuleName = $request->getModule(false);
 		$listViewModel = Settings_Vtiger_ListView_Model::getInstance($qualifiedModuleName);
-		$recordExists = $moduleModel->MailBoxExists();
-		$scannerRecordModels = $recordModel->getAll();
+		$recordExists = Settings_MailConverter_Module_Model::MailBoxExists();
+		$recordModel = Settings_MailConverter_Record_Model::getAll();
 		$viewer = $this->getViewer($request);
         
 		$viewer->assign('LISTVIEW_LINKS', $listViewModel->getListViewLinks());
-		$viewer->assign("MODULE_MODEL", Settings_Vtiger_Module_Model::getInstance($qualifiedModuleName));
-		$viewer->assign("MAILBOXES", $moduleModel->getMailboxes());
+		$viewer->assign('MODULE_MODEL', Settings_Vtiger_Module_Model::getInstance($qualifiedModuleName));
+		$viewer->assign('MAILBOXES', Settings_MailConverter_Module_Model::getMailboxes());
 	
-		$viewer->assign("MODULE_NAME", $moduleName);
-		$viewer->assign("QUALIFIED_MODULE_NAME", $qualifiedModuleName);
+		$viewer->assign('MODULE_NAME', $moduleName);
+		$viewer->assign('QUALIFIED_MODULE_NAME', $qualifiedModuleName);
 		$viewer->assign('CRON_RECORD_MODEL', Settings_CronTasks_Record_Model::getInstanceByName('MailScanner'));
 		$viewer->assign('RECORD_EXISTS', $recordExists);
 	
 		if ($scannerId) {
 		    $viewer->assign('SCANNER_ID', $scannerId);
-		    $viewer->assign("RECORD", $scannerRecordModels[$scannerId]);
+		    $viewer->assign('RECORD', $recordModel[$scannerId]);
 		    $viewer->assign('SCANNER_MODEL', Settings_MailConverter_Record_Model::getInstanceById($scannerId));
 		    $viewer->assign('RULE_MODELS_LIST', Settings_MailConverter_RuleRecord_Model::getAll($scannerId));
-		    $viewer->assign('FOLDERS_SCANNED', $moduleModel->getScannedFolders($scannerId));
-            $viewer->assign('MAILROOM_LISTVIEW_URL', $mailroomListViewURL);
-            
+		    $viewer->assign('FOLDERS_SCANNED', Settings_MailConverter_Module_Model::getScannedFolders($scannerId));
 		}
-		$viewer->view("RulesList.tpl", $qualifiedModuleName);
+		$viewer->view('RulesList.tpl', $qualifiedModuleName);
     }
     
     /**
@@ -59,7 +51,6 @@ class Settings_MailConverter_List_View extends Settings_Vtiger_Index_View {
 		$moduleName = $request->getModule();
 
 		$jsFileNames = array(
-            'modules.Settings.Vtiger.resources.List',
 			"modules.Settings.$moduleName.resources.List"
 		);
 
diff --git a/modules/Settings/MailConverter/views/RuleAjax.php b/modules/Settings/MailConverter/views/RuleAjax.php
index 32e377efbe1363a4a0601a36d76bcaa3cc8ddf92..2cc05a2ecf26be067791e2e49147e14f7daae372 100644
--- a/modules/Settings/MailConverter/views/RuleAjax.php
+++ b/modules/Settings/MailConverter/views/RuleAjax.php
@@ -1,31 +1,31 @@
-<?php
-/*+***********************************************************************************
- * The contents of this file are subject to the vtiger CRM Public License Version 1.0
- * ("License"); You may not use this file except in compliance with the License
- * The Original Code is:  vtiger CRM Open Source
- * The Initial Developer of the Original Code is vtiger.
- * Portions created by vtiger are Copyright (C) vtiger.
- * All Rights Reserved.
- *************************************************************************************/
-
-class Settings_MailConverter_RuleAjax_View extends Settings_Vtiger_IndexAjax_View {
-	
-	public function process(Vtiger_Request $request) {
-		$scannerId = $request->get('scannerId');
-		$ruleId = $request->get('record');
-		$qualifiedModuleName = $request->getModule(false);
-		$moduleName = $request->getModule();
-
-		$viewer = $this->getViewer($request);
-
-		$viewer->assign('SCANNER_ID', $scannerId);
-		$viewer->assign('SCANNER_MODEL', Settings_MailConverter_Record_Model::getInstanceById($scannerId));
-		$viewer->assign('RULE_MODEL', Settings_MailConverter_RuleRecord_Model::getRule($scannerId,$ruleId));
-
-		$viewer->assign('MODULE_NAME', $moduleName);
-		$viewer->assign('QUALIFIED_MODULE', $qualifiedModuleName);
-
-		$viewer->view('Rule.tpl', $qualifiedModuleName);
-	}
-}
-?>
+<?php
+/*+***********************************************************************************
+ * The contents of this file are subject to the vtiger CRM Public License Version 1.0
+ * ("License"); You may not use this file except in compliance with the License
+ * The Original Code is:  vtiger CRM Open Source
+ * The Initial Developer of the Original Code is vtiger.
+ * Portions created by vtiger are Copyright (C) vtiger.
+ * All Rights Reserved.
+ *************************************************************************************/
+
+class Settings_MailConverter_RuleAjax_View extends Settings_Vtiger_IndexAjax_View {
+	
+	public function process(Vtiger_Request $request) {
+		$scannerId = $request->get('scannerId');
+		$ruleId = $request->get('record');
+		$qualifiedModuleName = $request->getModule(false);
+		$moduleName = $request->getModule();
+
+		$viewer = $this->getViewer($request);
+
+		$viewer->assign('SCANNER_ID', $scannerId);
+		$viewer->assign('SCANNER_MODEL', Settings_MailConverter_Record_Model::getInstanceById($scannerId));
+		$viewer->assign('RULE_MODEL', Settings_MailConverter_RuleRecord_Model::getRule($scannerId,$ruleId));
+
+		$viewer->assign('MODULE_NAME', $moduleName);
+		$viewer->assign('QUALIFIED_MODULE', $qualifiedModuleName);
+
+		$viewer->view('Rule.tpl', $qualifiedModuleName);
+	}
+}
+?>