
<%@page import="com.sapphire.security.encryption.EncryptionUtil"%>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="security" uri="http://www.springframework.org/security/tags"%>
<%@page import="org.xnap.commons.i18n.I18n"%>
<%@ page import="com.sapphire.base64util.Base64"%>

<%@ include file="SapphireStdIncludes.jsp" %>
<%@include file="EXTJSIncludes-4.jsp" %>
<script type="text/javascript" src="ext/examples/ux/BoxSelect.js"></script>
<link type="text/css" href="ext/examples/ux/css/boxselect.css" media="screen" rel="Stylesheet"  />
<html>
<head>
<%
    I18n i18n = Sapphire.LANGUAGE_MAP.get((String) session.getAttribute("LANGUAGE_UNICODE"));
%>
<%@ include file="SapphireStdCSS.jsp" %>
<%@ taglib uri="/WEB-INF/ajaxtld/ajaxtags.tld" prefix="ajax" %>
 <script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxtags-1.2-beta1.js"></script>
<style type="text/css">
    .contentBlock dt{
    float: none;
    width: auto;
    text-align: inherit;
    }
    .contentBlock dd{
    float: none;
    width: auto;
    }
    .contentBlock dl{
        float: none;
        width: auto;
    }
        #text {margin:50px auto; width:500px}

        .hotspot {color:#900; padding-bottom:1px; cursor:pointer;}

        #tt {position:absolute;  display:block;  bgcolor : #666666;}
        #tttop {display:block; height:5px; margin-left:5px; background : #666666; overflow:hidden; border-top-left-radius: 15px; border-top-right-radius: 15px;}
        #ttcont {display:block; padding:2px 12px 3px 7px; margin-left:5px; background:#666; color:#FFF}
        #ttbot {display:block; height:5px; margin-left:5px; background : #666666; overflow:hidden; border-bottom-right-radius: 15px;}
		#navigation .timeStamp,#header_new #mainactions {
			font-size: 12px;
			line-height: 10px;
		}
		body{
			background-color:#98a2b0!important
		}
		#navigation ul li a:hover,#navigation ul li a,body a:hover{
			text-decoration:none
		}
</style>
<script type="text/javascript">

 /*
  * USER DEFINED FUNCTIONS COMES HERE
  */
 var addflag = 0;
 function changeServiceDummyDiv1(){
    var loadAddFields=document.getElementById("ServiceDummyDiv1");
    loadAddFields.options[0].selected=true;
    loadAddFields.onchange();
    
    
}
 function changeServiceDummyDiv2(){
    var loadAddFields=document.getElementById("ServiceDummyDiv2");
    loadAddFields.options[0].selected=true;
    loadAddFields.onchange();
 }
 function changeServiceDummyDiv3(){
    var loadAddFields=document.getElementById("category");
    loadAddFields.options[0].selected=true;
    loadAddFields.onchange();
 }
 function changeServiceDummyDiv4(){
    var loadAddFields=document.getElementById("ServiceDummyDiv3");
    loadAddFields.options[0].selected=true;
    loadAddFields.onchange();
 }
 var lastCartUpdate = 0;
var req;
function test()
{
    var configuredTransport ="";
    if(document.getElementById("Transport3").checked){
        configuredTransport = "Exchange";
    }else if(document.getElementById("Transport4").checked){
        configuredTransport = "ModernAuth";
    }else if(document.getElementById("Transport5").checked){
        configuredTransport = "ModernIMAP";
    }else{
        configuredTransport = "POPIMAP";
    }
    var url="";
    var storename = "";
    var smtpaddr = document.form1.pop3server.value;
    var fromaddr = document.form1.fromEmailAddres.value;
    var portno = document.form1.pop3port.value;
    var uname = document.form1.user.value;
    var pwd = document.form1.pass.value;

    var check_val=1;
    var isTLS = 0;
    var isSSL=0;
    var pollTest = 1;
    var serverName = document.form1.pop3server.value;
    if(document.form1.sslenable.checked == true){
        isSSL=1;
    }
    if(document.getElementById("Transport1").checked){
        storename = "pop3";
    }
    else if(document.getElementById("Transport2").checked){
        storename = "imap";
    }
    document.form1.testButton.disabled=true;
    if( configuredTransport !== 'Exchange' && configuredTransport !== 'ModernAuth' && configuredTransport !=='ModernIMAP'){
        url="MailSmtp?transportConfig=POPIMAP&smtpaddr="+encodeURIComponent(smtpaddr)+"&fromaddr="+encodeURIComponent(fromaddr)+"&check_val="+encodeURIComponent(check_val)+"&portno="+encodeURIComponent(portno)+"&uname="+encodeURIComponent(uname)+"&pwd="+encodeURIComponent(pwd)+"&isTLS="+encodeURIComponent(isTLS)+"&isSSL="+encodeURIComponent(isSSL)+"&storename="+storename+"&pollTest="+pollTest+"&serverName="+serverName;
    }else if( configuredTransport === 'ModernIMAP' || configuredTransport === 'ModernAuth'){
        var accessToken = document.getElementById("accessToken").value;
        var expiresIn = document.getElementById("expiresIn").value;
        var refreshToken= document.getElementById("refreshToken").value;
        var mailDetailsId = document.getElementsByName("MailDetails_ID")[0].value;
        if (accessToken == "" || refreshToken == "" || expiresIn == "") {
            alert("Please authorize access");
            document.form1.provider.focus();
            document.form1.testButton.disabled=false;
            return false;
        }
        if( configuredTransport === 'ModernAuth'){
            url="MailSmtp?transportConfig=ModernAuth&mailProfileId="+document.form1.provider.value+"&smtpaddr="+encodeURIComponent(smtpaddr)+"&fromaddr="+encodeURIComponent(fromaddr)+"&check_val="+encodeURIComponent(check_val)+"&portno="+encodeURIComponent(portno)+"&uname="+encodeURIComponent(uname)+"&pwd="+encodeURIComponent(pwd)+"&isTLS="+encodeURIComponent(isTLS)+"&isSSL="+encodeURIComponent(isSSL)+"&storename="+storename+"&pollTest="+pollTest+"&serverName="+serverName+"&accessToken="+accessToken+"&refreshToken="+refreshToken+"&expiresIn="+expiresIn+"&mailDetailsId="+mailDetailsId;
        }else{
            url="MailSmtp?transportConfig=ModernIMAP&mailProfileId="+document.form1.provider.value+"&smtpaddr="+encodeURIComponent(smtpaddr)+"&fromaddr="+encodeURIComponent(fromaddr)+"&check_val="+encodeURIComponent(check_val)+"&portno="+encodeURIComponent(portno)+"&uname="+encodeURIComponent(uname)+"&pwd="+encodeURIComponent(pwd)+"&isTLS="+encodeURIComponent(isTLS)+"&isSSL="+encodeURIComponent(isSSL)+"&storename="+storename+"&pollTest="+pollTest+"&serverName="+serverName+"&accessToken="+accessToken+"&refreshToken="+refreshToken+"&expiresIn="+expiresIn+"&mailDetailsId="+mailDetailsId;
        }
    
        //url="MailSmtp?transportConfig=ModernIMAP&mailProfileId="+document.form1.provider.value+"&smtpaddr="+encodeURIComponent(smtpaddr)+"&fromaddr="+encodeURIComponent(fromaddr)+"&check_val="+encodeURIComponent(check_val)+"&portno="+encodeURIComponent(portno)+"&uname="+encodeURIComponent(uname)+"&pwd="+encodeURIComponent(pwd)+"&isTLS="+encodeURIComponent(isTLS)+"&isSSL="+encodeURIComponent(isSSL)+"&storename="+storename+"&pollTest="+pollTest+"&serverName="+serverName;
    }else{
        url="MailSmtp?transportConfig=Exchange&smtpaddr="+encodeURIComponent(smtpaddr)+"&fromaddr="+encodeURIComponent(fromaddr)+"&check_val="+encodeURIComponent(check_val)+"&portno="+encodeURIComponent(portno)+"&uname="+encodeURIComponent(uname)+"&pwd="+encodeURIComponent(pwd)+"&isTLS="+encodeURIComponent(isTLS)+"&isSSL="+encodeURIComponent(isSSL)+"&storename="+storename+"&pollTest="+pollTest+"&serverName="+serverName;
    }
    document.getElementById("showProcessMsg").style.display="block";
    if(window.XMLHttpRequest){
            req = new XMLHttpRequest();
    }else if(window.ActiveXObject){
            req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    req.onreadystatechange = getReadyStateHandler(req, printData);
    req.open("GET", url, true);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send(null);
}
function printData(validXML){
    
  	var cart = validXML.getElementsByTagName("Root")[0];
	var generated = cart.getAttribute("generated");
	if(generated > lastCartUpdate){
		lastCartUpdate = generated;
		var rowdata=cart.getElementsByTagName("Row-Data");
		var nrows = rowdata.length;
		var resp = "";
		for (var I = 0 ; I < nrows; I++) {
                        var item = rowdata[I];
			resp = item.getElementsByTagName("Row-Value")[0].firstChild.nodeValue;
			document.getElementById("showProcessMsg").style.display="none";
			alert(resp);
			
		}
			document.form1.testButton.disabled=false;
	}
  }
  function scan(validXML){
    
  	var cart = validXML.getElementsByTagName("Root")[0];
	var generated = cart.getAttribute("generated");
	if(generated > lastCartUpdate){
		lastCartUpdate = generated;
		var rowdata=cart.getElementsByTagName("Row-Data");
		var nrows = rowdata.length;
		var resp = "";
		for (var I = 0 ; I < nrows; I++) {
                        var item = rowdata[I];
			resp = item.getElementsByTagName("Row-Value")[0].firstChild.nodeValue;
			document.getElementById("showProcessMsg").style.display="none";
                        if((resp.indexOf("Authentication Failed. Invalid Username or password.") === 0) || (resp.indexOf("Unable to connect to server. Check server name and port.") === 0))
                        {
                            alert(resp);
                            document.form1.scanBtn.disabled=false;
                            return;
                        }
                        else
                        {
                            var folderArray = resp.split("\n");
                            var foldersList = document.getElementById("folderslist");
                            var option ;
                            var flag;
                            for(var i=0; i<folderArray.length-1; i++)
                            {
                                flag = 0;
                                for(var j=0; j<foldersList.length; j++)
                                {
                                    if(foldersList.options[j].value.toLowerCase() == folderArray[i].toLowerCase())
                                    {   
                                        flag = 1 ;
                                    }
                                }
                                if( flag !=  1)        
                                {
                                    option = document.createElement("option");
                                    option.text = folderArray[i];
                                    foldersList.add(option);
                                }
                            }
                             <%if(session.getAttribute("SERVICEDESK_NEWUI_PAGE")!= null && request.getParameter("isNewUIAvailable")!=null && request.getParameter("isNewUIAvailable").equals("yes")){%>
                                jQuery("#folderslist").multipleSelect("refresh")
                             <%}%>       
                        }
		 }
			document.form1.scanBtn.disabled=false;
	 }
  }
function initProgress() {
  Element.show('progressMsg');
}

function resetProgress() {

  Effect.Fade('progressMsg');
}

function reportError() {
  
   if ($('model').options.length == 0) {
      $('errorMsg').innerHTML = "Dropdown busted!";
  }
  
  
  $('errorMsg').innerHTML = "Html content busted!";
  Element.show('errorMsg');
  setTimeout("Effect.DropOut('errorMsg')", 25000);
}

var req;
var lastCartUpdate = 0;


function getReadyStateHandler(req, responseXmlHandler) {
     return function () {
	
	if (req.readyState == 4) {

		if (req.status == 200) {
			
			responseXmlHandler(req.responseXML);
			    } 
	       }else{

		   }
	     }
   }

        function validateFilters() {
            var filters = $('#builder').queryBuilder('getRules');
	        var flag = 0;
			
			 if($('.rules-list li').length === 0){
				 flag = 1;
				 return true;
			 }
			 
			 $('.rules-list li.rule-container#builder_rule_0.has-error').each(function() {
             if ($(this).find('.rule-operator-container select').length === 0 && $('.rules-list li').length === 1 && $('#builder').queryBuilder('getRules') === null && $('.rules-list li').length === 1) {
				flag = 1;
				return true;
             }
             });
			 

            if (filters === null && flag !== 1) {
                alert('Please provide a value for the filter.');
                return false;
            }
			
            return true;
        }


	function validatePage(e)
	{

			if(document.form1.configuration.value==""){
					
					alert("Enter Configuration Name");
					document.form1.configuration.focus();
					return;
					
		   }
                    if(document.getElementById('serverName').style.display != "none"){
                       if(document.form1.pop3server.value==""){

                                           alert("Enter Server Name");
                                           document.form1.pop3server.focus();
                                           return;

                      }
                  }
                  var configuredTransport ="";
                if(document.getElementById("Transport3").checked){
                    configuredTransport = "Exchange";
                }else if(document.getElementById("Transport4").checked){
                    configuredTransport = "ModernAuth";
                }else if(document.getElementById("Transport5").checked){
                    configuredTransport = "ModernIMAP";
                }else{
                    configuredTransport = "POPIMAP";
                }
                if(document.getElementById('userdetailblock4').style.display !== "none"){
                    //validation
                        if(document.form1.autoDiscoveryUrl1.checked===true && document.form1.discoveryUrlValue.value==="")
                        {
                            alert("Please specify the auto-discovery url");
                            document.AJAX.discoveryUrlValue.focus();
                            return;
                        }
                }
                if(document.getElementById('authorizeAccessDiv').style.display != "none" && configuredTransport === 'ModernIMAP' ){
                    if(document.form1.sslenable.checked == false){
                        alert("Please enable SSL");
                        document.form1.sslenable.focus();
                        return;
                    }
                }
                if(document.getElementById('providerRow').style.display != "none"){
                    var provider = document.form1.provider.value;
                    if (provider == "") {
                        alert("Please select Mail Profile");
                        document.form1.provider.focus();
                        return false;
                    }
                }
//Function to validate the polling EmailID

                    if(document.getElementById('userdetailblock').style.display != "none"){
		           var x = document.form1.fromEmailAddres.value;
                           if (x == "") {
                                alert("Please enter Polling Email Id");
                                  return false;
                                        }else{ 
                                            var reg = /^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,})$/;
                                            if (reg.test(x) == false) 
                                             {
                                               alert("Your mail ID ' "+x+" ' is not correct");
                                               return false;
                                              }
                                            }
                    }
                                
                if(document.getElementById('userdetailblock2').style.display != "none"){
                   if(document.form1.user.value=="" && !(configuredTransport === 'ModernIMAP' || configuredTransport === 'ModernAuth')){
					
					alert("Please Enter UserName");
					document.form1.user.focus();
					return;
					
		   }
                }
                if(document.getElementById('userdetailblock3').style.display != "none"){
                   if(document.form1.PageType.value == ""){
		   if(document.form1.pass.value==""){
					
                        alert("Please Enter Password");
                        document.form1.pass.focus();
                        return;
					
		   }
                   }else{
                       if(document.form1.pass.value==""){
                            alert("Please re-enter the \"Password\"");
                            document.form1.pass.focus();
                            return;
					
                        }
                   }
               }
                 //token validation
               if(document.getElementById('authorizeAccessDiv').style.display != "none"){
                    var accessToken = document.form1.accessToken.value;
                    var refreshToken = document.form1.refreshToken.value;
                    var expiresIn = document.form1.expiresIn.value;
                    if (accessToken == "" || refreshToken == "" || expiresIn == "") {
                        alert("Please authorize access");
                        document.form1.provider.focus();
                        return false;
                    }else{
                       var now = new Date();
                       var expiryDateTime = new Date(document.getElementById("expiryDate").value);
                       var res = 0; 
                       if (now > expiryDateTime) {    
                            clearTokenDetails();
                            alert("Please authorize again as token is expired");
                            document.form1.provider.focus();
                            return false;
                        }
                    }
                }  
                   if (document.form1.messagelimit.value =="")
                   {
                       alert("Please enter \"Maximum Message Size\"");
                       document.form1.messagelimit.focus();
                       return;
                   }
                   
                   if (parseInt(document.form1.messagelimit.value) <0)
                   {
                       alert("The \"Maximum Message Size\" value should not be less than 0");
                       document.form1.messagelimit.focus();
                       return;
                   }
                   if (parseInt(document.form1.messagelimit.value) >100)
                   {
                       alert("The \"Maximum Message Size\" value should not be greater than 100");
                       document.form1.messagelimit.focus();
                       return;
                   }

                    if(document.form1.domlook.checked){
                        if(document.getElementById("accessrowcount").value == 0){
                             if(document.getElementById("domainName").value==""){
                                   alert("Please enter a domain name");
                                   document.form1.domainName.focus();
                                   return;
                                } 
                             if(document.getElementById("users").value==""){
                                   alert("Please select an user");
                                   document.form1.users.focus();
                                   return;
                                }   
                            alert("Please add at least one Domain Lookup");
                            return;
                         }
                     }
                     var isValid = validateFilters();
                     
            if (isValid) {
                    var sql_raw = $('#builder').queryBuilder('getSQL', false);
                    if(sql_raw === null){
                        $("#returnQueryBuilderData").val("");
            }else{
                        $("#returnQueryBuilderData").val(sql_raw.sql);
            }
            }else{
                return;
            }
		   if(document.form1.project.value==""){
      
				alert("Please select project");
				document.form1.project.focus();
				return;
	 		  }
		    if(document.form1.ServiceLine.value=="" || document.form1.ServiceLine.value === "0"){
				
				alert("Please select Service");
				document.form1.ServiceLine.focus();
				return;
	 		  }
			
			if(document.form1.category.value=="" || document.form1.category.value === "0"){
				
				alert("Please select Category");
				document.form1.category.focus();
				return;
	 		  }
			if(document.form1.submit_through.value==""){
				
				alert("Please select Mode");
				document.form1.submit_through.focus();
				return;
	 		  }
          var compregex=/(^\+?\d\d*)$/;
                        if(document.form1.pop3port.value==""){

                                      alert("Please enter Port number");
                                      document.form1.pop3port.focus();
                                      return;
                        }
		  if(document.form1.pop3port.value!="")
    	  {
		  
			  if(!compregex.test(document.form1.pop3port.value))
			  {
		      alert("Port number cannot contain charaters or special characters or spaces");
		      document.AJAX.pop3port.focus();
			  	return;
			  }
	  
	      }
                  if(document.form1.domainFilter1.checked==true && document.form1.filterValue.value=="")
                      {
                          alert("Please specify the domain filter value");
                          document.AJAX.filterValue.focus();
			  	          return;
                      }
	    
	    
	    if(document.form1.popauth.value!="")
    	{
        if(!compregex.test(document.form1.popauth.value))
		{
	      alert("APOP Authentication cannot contain charaters or special characters or spaces");
	      document.AJAX.popauth.focus();
		  	return;
		 }
		}
		  
		 


		
        var foldersList = document.getElementById("folderslist");
        for(var i=0; i<foldersList.length; i++)
        {
            if(foldersList.options[i].selected == "true")
                {
                    foldersList.options[i].selected == "true";
                }
        }
//      document.getElementById("ruleContent").value = ruleContent;
      
      if(document.form1.emailcom.checked)
      {
          if(document.form1.emailsub.value == "")
          {
              alert("Please enter the email subject");
              document.form1.emailsub.focus();
              return;
          }
          if(document.form1.emaildel.value == "")
          {
              alert("Please enter the email command delimiter");
              document.form1.emailsub.focus();
              return;
          }
      }
      if(document.getElementById("emailsub").value.length >= 255){
            alert("Email subject filter must be less than 255 characters");
            document.form1.emailsub.focus();
            return;
        }
      if(document.getElementById("emaildel").value.length >= 255){
            alert("Email command delimiter must be less than 255 characters");
            document.form1.emaildel.focus();
            return;
        }
        var emailcomregex =/[^a-z0-9~!@#$%^&*\s]/i;
        if(emailcomregex.test(document.form1.emailsub.value))
        {
            alert("The email subject filter should contain special characters only from the list specified in help");
            document.form1.emailsub.focus();
            return;
        }    
        var emaildelimiterregex =/[^~!@#$%^&*]/i;
        if(emaildelimiterregex.test(document.form1.emaildel.value))
        {
            alert("The email command delimiter should contain special characters only from the list specified in help");
            document.form1.emaildel.focus();
            return;
        }    

      var xmlDoc=null;
      var status ="true";
                if(window.XMLHttpRequest)
                {
                    xmlDoc = new XMLHttpRequest();
		}
                else if(window.ActiveXObject)
                {
                    xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
		}
                var configurationName = "";
                if(document.getElementById("configuration") != null)
                    configurationName = document.getElementById("configuration").value;
                var mailDetailsId = "0";
                if ( document.getElementsByName("MailDetails_ID")[0] != null && document.getElementsByName("MailDetails_ID")[0] != undefined)
                    mailDetailsId = document.getElementsByName("MailDetails_ID")[0].value;
                var url="./MailServerConfiguration?mailConfigurationCheck=yes&configurationName="+configurationName.trim()+"&MailDetails_ID="+mailDetailsId;
                xmlDoc.open("GET", url, false);
		xmlDoc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlDoc.send(null);
		if(xmlDoc.readyState == 4)
                {
                    if (xmlDoc.status == 200) 
                    {
                        status=xmlDoc.responseText;
                        if (status.trim() == "true" )
                        {
                            alert("Duplicate configuration name. Please enter some other name");
                            return false;
                        }
                    }
		}
                
     document.form1.submit();
}
function hideApop(){
    clearTokenDetails();
    document.getElementById("serverName").style.display="";
    document.getElementById("sslRow").style.display="";
    document.getElementById("portRow").style.display="";
    document.getElementById("inboxDiv").style.display="";
    document.getElementById("apopRow").style.display="none";
    document.getElementById("providerRow").style.display="none";
    document.getElementById("userdetailblock").style.display="";
    document.getElementById("userdetailblock2").style.display="";
    document.getElementById("userdetailblock3").style.display="";
    document.getElementById("userdetailblock4").style.display="none";
    document.getElementById("authorizeAccessDiv").style.display="none";
    document.getElementById("user").disabled=false;
    document.getElementById("userMouseOverId").style.display="none";
    if(document.getElementById("sslenable").checked){
        document.getElementById("pop3port").value = 993;
    }
    else {
        document.getElementById("pop3port").value = 143;
    }
 }
function showApop(){
    clearTokenDetails();
    document.getElementById("serverName").style.display="";
   document.getElementById("sslRow").style.display="";
   document.getElementById("portRow").style.display="";
   document.getElementById("inboxDiv").style.display="none";
    document.getElementById("apopRow").style.display="";
    document.getElementById("providerRow").style.display="none";
    document.getElementById("userdetailblock").style.display="";
    document.getElementById("userdetailblock2").style.display="";
    document.getElementById("userdetailblock3").style.display="";
    document.getElementById("userdetailblock4").style.display="none";
    document.getElementById("authorizeAccessDiv").style.display="none";
    document.getElementById("user").readOnly=false;
    document.getElementById("userMouseOverId").style.display="none";
    if(document.getElementById("sslenable").checked){
        document.getElementById("pop3port").value = 995;
    }
    else {
        document.getElementById("pop3port").value = 110;
    }
 }
 function showExchange(){
     clearTokenDetails();
     document.getElementById("serverName").style.display="none"; //serverName
     document.getElementById("inboxDiv").style.display="none"; //sslRow,portRow
     document.getElementById("apopRow").style.display="none";
     document.getElementById("sslRow").style.display="none";
     document.getElementById("portRow").style.display="none";
     document.getElementById("providerRow").style.display="none";
     document.getElementById("userdetailblock").style.display="";
    document.getElementById("userdetailblock2").style.display="";
    document.getElementById("userdetailblock3").style.display="";
    document.getElementById("userdetailblock4").style.display="";
    document.getElementById("authorizeAccessDiv").style.display="none";
    document.getElementById("user").readOnly=false;
    document.getElementById("userMouseOverId").style.display="none";
 }
  function showModernAuth(){
      clearTokenDetails();
     document.getElementById("serverName").style.display="none"; //serverName
     document.getElementById("inboxDiv").style.display="none"; //sslRow,portRow
     document.getElementById("apopRow").style.display="none";
     document.getElementById("sslRow").style.display="none";
     document.getElementById("portRow").style.display="none";
     document.getElementById("providerRow").style.display="";
     document.getElementById("userdetailblock").style.display="";
    document.getElementById("userdetailblock2").style.display="";
    document.getElementById("userdetailblock3").style.display="none";
    document.getElementById("userdetailblock4").style.display="none";
    document.getElementById("authorizeAccessDiv").style.display="";
    document.getElementById("user").readOnly=true;
    document.getElementById("userMouseOverId").style.display="";
//     ajax call
    var mailProfileLoad = loadMailProfileDropDown(3); 
 }
 function showModernIMAP(){
     clearTokenDetails();
     document.getElementById("serverName").style.display=""; //serverName
     document.getElementById("inboxDiv").style.display=""; //sslRow,portRow
     document.getElementById("apopRow").style.display="none";
     document.getElementById("sslRow").style.display="";
     document.getElementById("portRow").style.display="";
     document.getElementById("providerRow").style.display="";
     document.getElementById("userdetailblock").style.display="";
    document.getElementById("userdetailblock2").style.display="";
    document.getElementById("userdetailblock3").style.display="none";
    document.getElementById("userdetailblock4").style.display="none";
    document.getElementById("authorizeAccessDiv").style.display="";
    document.getElementById("user").readOnly=true;
    document.getElementById("userMouseOverId").style.display="";
    if(document.getElementById("sslenable").checked){
        document.getElementById("pop3port").value = 993;
    }
    else {
        document.getElementById("pop3port").value = 143;
    }
//     ajax call
    var mailProfileLoad = loadMailProfileDropDown(2); 
 }
 function loadMailProfileDropDown(type){
    var provider = document.form1.providerSelected.value;
    var req=null;
    if(window.XMLHttpRequest){
        req = new XMLHttpRequest();
    }else if(window.ActiveXObject){
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var url="./MacroOperations?getMailProfiledetails=yes&type="+type;
    req.open("GET", url, false);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send(null);
    var result="";
    if(req.readyState == 4){
        if(req.status == 200){
            result=req.responseText;
        }
    }
    document.getElementById('provider').innerHTML=result;
    var pageType = document.form1.PageType.value;
    if(pageType == 'Edit'){
        var val = 0;
        for (i = 0; i < document.getElementById("provider").length; ++i){
            if (document.getElementById("provider").options[i].value == provider){
                document.getElementById('provider').value = provider;
                val =1;
                break;
            }
        }
        if(val == 0){
            document.getElementById('provider').value="";
        }
    }
    <%if(session.getAttribute("SERVICEDESK_NEWUI_PAGE")!= null){%>
    jQuery("#provider").multipleSelect("refresh");
    <%}%>
    return 1;
 }
function changePortNumber(){
    if(document.getElementById("sslenable").checked){
        if(document.getElementById("Transport1").checked){
            document.getElementById("pop3port").value = 995;
        }
        else if(document.getElementById("Transport2").checked || document.getElementById("Transport5").checked){
            document.getElementById("pop3port").value = 993;
        }
    }
    else{
        if(document.getElementById("Transport1").checked){
            document.getElementById("pop3port").value = 110;
        }
        else if(document.getElementById("Transport2").checked || document.getElementById("Transport5").checked){
            document.getElementById("pop3port").value = 143;
        }
    }
}
function showDomainBox(){
       if(document.form1.domainFilter1.checked==true){
           document.getElementById("filterDiv").style.display="";
       }
       else {
           document.getElementById("filterDiv").style.display="none";
       }
    
}
function showAutodiscoveryUrlBox(){
       if(document.form1.autoDiscoveryUrl1.checked==true){
           document.getElementById("autoDiscoveryUrlDiv").style.display="";
       }
       else {
           document.getElementById("autoDiscoveryUrlDiv").style.display="none";
       }
    
}
function scanMailbox(){
    var url="";
 
    var smtpaddr = document.form1.pop3server.value;
    var fromaddr = document.form1.fromEmailAddres.value;
    var portno = document.form1.pop3port.value;
    var uname = document.form1.user.value;
    var pwd = document.form1.pass.value;

    var serverName = document.form1.pop3server.value;
    var foldersList = document.getElementById("folderslist");
    var list = "";
    var pollTest = 1;
    var check_val=1;
    var isTLS = 0;
    var isSSL=0;
    var isIMAP = 0;
    var isScan = 1;
    var mailProfileId = 0;
    if(document.form1.sslenable.checked == true){
        isSSL=1;
    }
    if(document.getElementById("Transport2").checked){
        isIMAP = 1;
    }
    if(document.getElementById("Transport1").checked){
        storename = "pop3";
    }
    else if(document.getElementById("Transport2").checked){
        storename = "imap";
    }
    if(document.getElementById("Transport5").checked){
        isIMAP = 1;
        mailProfileId = document.getElementById("provider").value;
    }
    console.log("----------------mailProfileId :: "+mailProfileId);
     document.form1.scanBtn.disabled=true;
     if(document.getElementById("Transport5").checked){
        if (mailProfileId === "") {
            alert("Please select Mail Profile");
            document.form1.provider.focus();
            return false;
        }
        var accessToken = document.getElementById("accessToken").value;
        var expiresIn = document.getElementById("expiresIn").value;
        var refreshToken= document.getElementById("refreshToken").value;
        var mailDetailsId = document.getElementsByName("MailDetails_ID")[0].value;
        if (accessToken == "" || refreshToken == "" || expiresIn == "") {
            alert("Please authorize access");
            document.form1.provider.focus();
            document.form1.testButton.disabled=false;
            return false;
        }
         url="MailSmtp?transportConfig=ModernIMAP&mailProfileId="+document.form1.provider.value+"&smtpaddr="+encodeURIComponent(smtpaddr)+"&fromaddr="+encodeURIComponent(fromaddr)+"&check_val="+encodeURIComponent(check_val)+"&portno="+encodeURIComponent(portno)+"&uname="+encodeURIComponent(uname)+"&pwd="+encodeURIComponent(pwd)+"&isTLS="+encodeURIComponent(isTLS)
                                +"&isSSL="+encodeURIComponent(isSSL)+"&storename=&pollTest="+pollTest+"&isIMAP="+isIMAP+"&serverName="+serverName+"&isScan="+isScan
                                +"&accessToken="+accessToken+"&refreshToken="+refreshToken+"&expiresIn="+expiresIn+"&mailDetailsId="+mailDetailsId+"&mailProfileId="+mailProfileId;
     }else{
         url="MailSmtp?transportConfig=POPIMAP&smtpaddr="+encodeURIComponent(smtpaddr)+"&fromaddr="+encodeURIComponent(fromaddr)+"&check_val="+encodeURIComponent(check_val)+"&portno="+encodeURIComponent(portno)+"&uname="+encodeURIComponent(uname)+"&pwd="+encodeURIComponent(pwd)+"&isTLS="+encodeURIComponent(isTLS)+"&isSSL="+encodeURIComponent(isSSL)
                                +"&isIMAP="+isIMAP+"&serverName="+serverName+"&isScan="+isScan+"&pollTest="+pollTest+"&storename="+storename;
     }
     document.getElementById("showProcessMsg").style.display="block";
     if(window.XMLHttpRequest){
     			req = new XMLHttpRequest();
     		}else if(window.ActiveXObject){
     			req = new ActiveXObject("Microsoft.XMLHTTP");
		}
	req.onreadystatechange = getReadyStateHandler(req, scan);
	req.open("GET", url, true);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send(null);    
}
var hide=0;
var ruleContent = "";
function showhidepane(){
    
     if(hide==0){ 
        document.getElementById("builder").style.display="block";
        document.getElementById("PlusMinusImg").src="icon_minus.gif";
        document.getElementById("PlusMinusImg").title="Hide Spam Filtering Rules";
        hide=1;
     }else{
        document.getElementById("builder").style.display="none"; 
        document.getElementById("PlusMinusImg").src="icon_plus.gif";
        document.getElementById("PlusMinusImg").title="Show Spam Filtering Rules";
        hide=0;
    }
}
var flag = 0;
function showlookuppane(){
    
     if(flag==1){    
        document.getElementById("lookupDiv").style.display="none"; 
        document.getElementById("domLookupTr").style.display="none"; 
        document.getElementById("DomLookUpImg").src="icon_plus.gif";
        document.getElementById("DomLookUpImg").title="Show Email Command Rules";
        flag=0;
     }else{
         if(document.form1.domlook.checked)
         {
             document.getElementById("lookupDiv").style.display="";
         }
         else
         {
             document.getElementById("lookupDiv").style.display="none";
         }
        document.getElementById("domLookupTr").style.display="";
        document.getElementById("DomLookUpImg").src="icon_minus.gif";
        document.getElementById("DomLookUpImg").title="Hide Email Command Rules";
        flag=1;
    }
}

    
function displayemailcomDiv(){
    if(document.form1.emailcom.checked)
    {
        document.getElementById("emailcomDiv").style.display = "";
    }
    else
    {
        document.getElementById("emailcomDiv").style.display = "none";
    }
}
function displaydomlookup(){
    if(document.form1.domlook.checked)
    {
        document.getElementById("lookupDiv").style.display = "";
    }
    else
    {
        document.getElementById("lookupDiv").style.display = "none";
    }
}
var collapse = 0
function showemailcomdiv(){
    
     if(collapse==1){    
        document.getElementById("emailcomDiv").style.display="none"; 
        document.getElementById("emailEnableTr").style.display="none"; 
        document.getElementById("emailComPic").src="icon_plus.gif";
        document.getElementById("emailComPic").title="Show Email Command Rules";
        collapse=0;
     }else{
         if(document.form1.emailcom.checked)
         {
             document.getElementById("emailcomDiv").style.display="";
         }
         else
         {
             document.getElementById("emailcomDiv").style.display="none";
         }
        document.getElementById("emailEnableTr").style.display="";
        document.getElementById("emailComPic").src="icon_minus.gif";
        document.getElementById("emailComPic").title="Hide Email Command Rules";
        collapse=1;
    }
}
var tooltip=function(){
    
        var id = 'tt';
        var top = 3;
        var left = 3;
        var maxw = 450;
        var speed = 10;
        var timer = 20;
        var endalpha = 100;
        var alpha = 0;
        var tt,t,c,b,h;
        var ie = document.all ? true : false;
        return{
            show:function(v,w){
                
                if(tt == null){
                    tt = document.createElement('div');
                    tt.setAttribute('id',id);
                    t = document.createElement('div');
                    t.setAttribute('id',id + 'top');
                    c = document.createElement('div');
                    c.setAttribute('id',id + 'cont');
                    b = document.createElement('div');
                    b.setAttribute('id',id + 'bot');
                    tt.appendChild(t);
                    tt.appendChild(c);
                    tt.appendChild(b);
                    document.body.appendChild(tt);
                    tt.style.opacity = 0;
                    tt.style.filter = 'alpha(opacity=0)';
                    document.onmousemove = this.pos;
                }
                tt.style.display = 'block';
                c.innerHTML = v;
                tt.style.width = w ? w + 'px' : 'auto';
                if(!w && ie){
                    t.style.display = 'none';
                    b.style.display = 'none';
                    tt.style.width = tt.offsetWidth;
                    t.style.display = 'block';
                    b.style.display = 'block';
                }
                if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
                h = parseInt(tt.offsetHeight) + top;
                clearInterval(tt.timer);
                tt.timer = setInterval(function(){tooltip.fade(1)},timer);
            },
            pos:function(e){
                var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
                var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
                tt.style.top = (u - h) + 'px';
                tt.style.left = (l + left) + 'px';
            },
            fade:function(d){
                var a = alpha;
                if((a != endalpha && d == 1) || (a != 0 && d == -1)){
                        var i = speed;
                        if(endalpha - a < speed && d == 1){
                                i = endalpha - a;
                        }else if(alpha < speed && d == -1){
                                i = a;
                        }
                        alpha = a + (i * d);
                        tt.style.opacity = alpha * .01;
                        tt.style.filter = 'alpha(opacity=' + alpha + ')';
                }else{
                        clearInterval(tt.timer);
                        if(d == -1){tt.style.display = 'none'}
                }
            },
            hide:function(){
                clearInterval(tt.timer);
                tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
            }
        };
    }();
function mouseOverMessage(type){

        var description = "";
        if(type == "subjectLine"){
            description="If the specified string matches the subject line of an incoming email then that email will be considered for Email Command processing <br/><br/> \n\
                            Please specify the email subject filter string enclosed between the set of below special characters:  <br/><br/>\n\
                             ~, !, @, #, $, %, ^, & and * <br/><br/> \n\
                            Please note that the set of special characters used before and after the string should be the same <br/><br/> \n\
                            Examples of valid email subject filter strings: <br/><br/> \n\
                            #EmailAlert#, #Email Alert#, ##EmailAlert##, #@EmailAlert#@ etc <br/><br/> \n\
                            Examples of invalid email subject filter strings: <br/><br/>\n\
                            [EmailAlert}, #EmailAlert@, #EmailAlert##, #@EmailAlert@# etc";
        }else if(type == "delimiter"){
            description="Specify the Email Command Delimiter string to search in the body of an incoming email to identify the Email Commands<br/><br/>"
                        +" The Email Command Delimiter should contain only the following special characters without blank spaces between them:<br/><br/>"
                        +" ~, !, @, #, $, %, ^, & and *<br/><br/>" 
                        +" Examples of valid Email Command Delimiter strings: <br/><br/>" 
                        +" #, @, ##, @@, #@, ##@ etc <br/><br/>"
                        +" Examples of invalid Email Command Delimiter strings: <br/><br/>" 
                        +" # #, # / #, @ @, ##text## etc";
        }
        else if(type == "enableCommand")
        {
       	     description = "Using Email Command, the value of Fixed Fields (like Service, Category, Subcategory etc) and manually created Additional Fields for a specific record can be updated through email<br/>"
                            +" The Email Command feature is applicable only for a \"New\" incoming mail and will be processed only when the \"Submit Email as Ticket\" Setting Key is enabled (set to \"1\") in Settings -> Advanced System Settings -> Global Settings<br/>"
                            +" The Email Commands are specified in the email body enclosed within the Email Command Delimiters in the format \"Field Name=Value\", e.g. <br/>"
                            +" To set the Service of a record to \"Application Services\" and the Category to \"CRM\" , the Email Command will be (assuming that the configured Email Command Delimiter is ##): <br/><br/>"
                            +" ##Service=Application Services## <br/>"
                            +" ##Category=CRM## <br/><br/>"
                            +" Following are the supported Fixed Fields : <br/>"
                            +" Service, Category, Sub Category, Derived Field 1, Derived Field 2, Derived Field 3, Request Type, Urgency, Impact, Location, Department, Title, Description, CI(Asset)<br/><br/>"
                            +" Following are the supported Additional Fields : <br/>"
                            +" Text Box : Any value can be specified (cannot be multiple lines) e.g. ##Field Name=This is just for test## <br/>"
                            +" Text Area : Any value can be specified (can be multiple lines)<br/>"
                            +" Single Select Box : Any value that is present in the dropdown e.g. ##Field Name=value1## <br/> "
                            +" HTML Multi Select Box : Multiple values present in the select box one per line. e.g. ##Field Name=value1## ##Field Name=value2## <br/> "
                            +" ExtJs Searchable Multi Select Box : Multiple values present in the select box comma separated values e.g. ##Field Name=value1,value2## <br/>"
                            +" Check Box : Yes for selecting the check box, No for deselecting e.g. ##Field Name=Yes## ##Field Name=No## <br/> "
                            +" Radio Buttons : Any value which is present as options can be specified e.g. ##Field Name=value1## <br/>"
                            +" Date : Value in the format yyyy-mm-dd e.g. ##Field Name=2014-08-25## <br/> "
                            +" Date/Time : Value in the format yyyy-mm-dd hh:mm e.g. ##Field Name=2014-08-25 10:10## <br/><br/>"
                            +" Notes:<br/><br/> "
                            +" 1. Each Email Command should be an individual line in the email body and there should not be any blank space(s) at the end of each line  <br/>"
                            +" 2. The mail has to be composed in \"Plain Text\" or both \"Plain Text and HTML\" format<br/>"
                            +" 3. The field name mentioned in an Email Command should be available in the Service Desk Project <br/>"
                            +" 4. The value mentioned in an Email Command should be available in the Service Desk Project (except for those Additional Fields which are text box and text area fields) <br/>"
                            +" 5. The field name and value mentioned in an email command are not case sensitive <br/>"
                            +" 6. Ticket State cannot be set by an Email Command <br/>"
                            +" 7. The form fields like Title, Sub-Title, Grid Control, Static Grid etc are not supported for updating by Email Command";
        }
        else if(type == "apopNote")
        {
            description = "With APOP, your password is encrypted while being transmitted over the network. If your mail server supports this authentication then check this box";
        }
        else if(type == "domainFilterNote")
        {
            description = "The Email to Record feature allows you to convert emails from certain domains into records in your system. You can enter one or more domain names in the box, separated by commas. For example, to process only emails from gmail and outlook, enter gmail,outlook. The feature will ignore emails from other domains";
        }
        else if(type == "mailBoxNote")
        {
            description = "Mailbox folder processing will be applicable only for IMAP protocol<br/> Click on 'Scan Mailbox' to load list of available folders <br/> By default 'Inbox' will be selected & processed";
        }
        else if(type == "emailTemplate")
        {
            description = "Sample Email template for Email Command (with @@ as the delimiter):<br/><br/>@@Text Box=Setting the value from mail@@<br/><br/>"
                          +" @@Text area=This message(Including any attachments) is intended only for the addressee. If you are not the intended recipient or received this message by mistake, kindly notify the sender by E-mail & delete the message from the system.@@<br/><br/>"
                          +" @@Radio Button=Value 1@@ <br/><br/>"
                          +" @@Date/Time=1845-01-21 21:53@@ <br/><br/>"
                          +" @@Check Box=YES@@<br/><br/>"
                          +" @@Date=2014-12-09@@<br/><br/>"
                          +" @@Service=seRvice 1@@<br/><br/>"
                          +" @@category=CategoRy 1@@<br/><br/>"
                          +" @@suB Category=sub caTeGory 1@@<br/><br/>"
                          +" @@LoCation=Location 1@@<br/><br/>"
                          +" @@DepArtment=Department 1@@<br/><br/>"
                          +" @@CI=TKD/Laptop/0001@@<br/><br/>"
                          +" @@Title=Sample Title@@<br/><br/>"
                          +" @@DeScRipTion=Custom Fixed field command Description@@<br/><br/>"
                          +" @@Urgency=higH@@<br/><br/>"
                          +" @@ImpaCt=LoW@@<br/><br/>"
                          +" @@Request Type=Request for Information@@<br/><br/>"
                          +" @@Derived Field 1=Value@@<br/><br/>"
                          +" @@Derived Field 2=Value@@<br/><br/>"
                          +" @@Derived Field 3=Value@@<br/><br/>"
                          +" @@Searchable Multi Select Box=Value 1,Value 2@@<br/><br/>"
                          +" @@Single Select box=Value@@<br/><br/>"
                          +" @@HTML Multi Select Box=Value 1@@<br/><br/>"
                          +" @@HTML Multi Select Box=Value 2@@<br/><br/>";
        }
        else if(type == "sslNotes")
        {
            description = "If your mail server supports SSL, please check this box";
        }
        else if(type == "mainNote")
        {
            description = "Emails will be converted to records only if the setting key \"Enable or Disable Email Request Feature\" is set to \"1\" in Settings -> Advanced System Settings -> Global Settings";
        }
        else if(type == "autoSubmissionNote")
        {
            description = "Auto record submission feature will be enabled and disabled based on user selection";
        }
        else if(type == "messagelimit"){
            description = "Mails will be processed without attachments when it exceeds the configured message size. The default message size is 5 MB";
        }
        else if(type == "userModerAuth")
        {
            description = "User Name field is made readonly as its value will be automatically populated when authorized";
        }
        else if(type == "autoDiscoveryUrlNote")
        {
            description = "Provide valid Url for auto-discovery <br/><br/>\n\
                                        e.g. https://autodiscover-s.outlook.com/EWS/Exchange.asmx";
        }
        tooltip.show(' <strong>'+description+'</strong>');
}
function addDomain()
{
    if(document.form1.domlook.checked)
    {
        if(document.getElementById("domainName").value=="")
        {
             alert("Please enter a domain name");
             return;
        } 
        if(document.getElementById("users").value=="")
        {
             alert("Please select an user");
             return;
        }    
    }
    
    
    var userid = "";
    var domainname = "";
    
    if( userid === '' )
    {
        userid = document.getElementById("users").value;
    }
    else
    {
        userid += ","+document.getElementById("users").value;
    }
    
    if( domainname === '' )
    {
        domainname = document.getElementById("domainName").value;
    }
    else
    {
        domainname += ","+document.getElementById("domainName").value;
    }
    var domname = document.getElementById("domainName").value;
    var rowcount= parseInt(document.getElementById('accessrowcount').value);
   
    if( rowcount > 0 )
    {
        var tempDomName = document.getElementById("globalDomName").value.split(",");
        
        for(var i=0;i<tempDomName.length;i++)
        {
            if(tempDomName[i].toLowerCase()==domname.toLowerCase())
            {
                alert("Domain name already exists");
                document.form1.domainName.focus();
                return;
            }
        }
    }
    
    var accessRowCount=parseInt(document.getElementById('accessrowcount').value);
    accessRowCount++;
    
    var parentDiv = document.getElementById('dynamicRow_Domain');
    var divIdName = "Div_"+accessRowCount+"_Domain";
    var newdiv = document.createElement('div');
    newdiv.setAttribute("id",divIdName);
    
    newdiv.innerHTML = "<table width=\"100%\" border=\"0\"  class=\"ruleList\"><tr class='formfield'><td align=\"center\" width=\"10%\" class=\"formfield\"><a href=\"javascript:;\" class=\"delete1\" title=\"Delete\" onclick=\"removeDom(\'"+divIdName+"\')\"><img border=\"0\" src=\"fault_x.gif\" width=\"12\" height=\"12\" class=\"deleteRule\"></a></td>"+
                       "<input type=\"hidden\" name=\"uservalues\" id=\"uservalues\" value=\""+userid+"\">"+
                       "<input type=\"hidden\" name=\"domainvalues\" id=\"domainvalues\" value=\""+domainname+"\">"+
                       "<td  bgcolor=\"#FFFFFF\" width=\"45%\" align=\"center\" class=\"formfield\">"+document.getElementById("domainName").value+"</td>"+
                       "<td  bgcolor=\"#FFFFFF\" width=\"45%\" align=\"center\" class=\"formfield\">"+document.getElementById("username").value+"</td>"+
                       "</tr></table>";
    parentDiv.appendChild(newdiv);
    document.getElementById('accessrowcount').value = accessRowCount;
    addflag++;
    document.getElementById('addflag').value = addflag;
    document.getElementById("globalDomName").value += ","+domainname;

}
function removeDom(divNum,sno){    
    
     var  deletedsno = document.getElementById('deleted_sno').value;
    if(sno != undefined){
        if(deletedsno == ""){
            deletedsno=sno;
        }
        else{
            deletedsno=deletedsno+" , "+sno;
        }
     }
    
    document.getElementById('deleted_sno').value= deletedsno;
    var accessRowCount_remove = parseInt(document.getElementById('accessrowcount').value);    
    accessRowCount_remove--;
     
    var parentDiv = document.getElementById('dynamicRow_Domain');
    var divToDelete = document.getElementById(divNum);
    var values = divToDelete.innerHTML;
    value = values.split('id="domainvalues"');
    
    if(value[1] != undefined)
    {
        var deletedDomain = value[1].substr(8,value[1].indexOf("com")-5);
        document.getElementById("globalDomName").value = document.getElementById("globalDomName").value.replace(deletedDomain,"");
    }
    
    parentDiv.removeChild(divToDelete);
    document.getElementById('accessrowcount').value = accessRowCount_remove;  
}
function authAccess(){
    var provider = "";
    if(document.getElementById('providerRow').style.display != "none"){
        provider = document.form1.provider.value;
        if (provider == "") {
            alert("Please select Mail Profile");
            document.form1.provider.focus();
            return false;
        }
    }
    var openUrl="";
    var req=null;
    if(window.XMLHttpRequest){
        req = new XMLHttpRequest();
    }else if(window.ActiveXObject){
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var url="./MacroOperations?getAuthroizeAccessURL=yes&mailProfile="+provider;
    req.open("GET", url, false);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send(null);
    var result="";
    if(req.readyState == 4){
        if(req.status == 200){
            openUrl=req.responseText;
        }
    }
    window.open(openUrl,'popup','width=600,height=600');
}
function HandlePopupResult(result1,result2,result3,result4,result5) {
    document.getElementById("accessToken").value=result1;
    document.getElementById("expiresIn").value=result2;
    document.getElementById("refreshToken").value=result3;
    document.getElementById("expiryDate").value=result4;
    document.getElementById("user").value=result5;
}
function clearTokenDetails(){
    if(document.getElementById('authorizeAccessDiv').style.display != "none"){
        document.getElementById("accessToken").value="";
        document.getElementById("expiresIn").value="";
        document.getElementById("refreshToken").value="";
        document.getElementById("expiryDate").value="";
        var pageType = document.form1.PageType.value;
        if(pageType !== 'Edit'){
            document.getElementById("user").value="";
        }
    }
}  
</script>
<script src="assets/js/jquery.min.js"></script>
<script src="js/sql_parser.js"></script>
<script src="js/query-builder.standalone.min.js"></script>
<link type="text/css" href="css/query-builder.default.min.css" media="screen" rel="Stylesheet"  />
<link type="text/css" href="css/querybuilder.css" media="screen" rel="Stylesheet"  />
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
</head>

<body class="etrConfig">


 <%@ include file="toptable.jsp" %>
  <div id="mainContentArea1" class="mailServerConfigAddEdit">
   <form name="form1" id="form1" method="post" action="MailServerConfiguration"> 
<security:csrfInput/>
      <table width="100%" border="0" height="70%" cellspacing="0" cellpadding="0" align="center">
          <tr>         
            <td align="center" valign="top" width="98%" >
	      	  <table width="100%" border="0" cellspacing="0" cellpadding="0">
		       <tr>
                 <!-- Td to define the Top Tabs starts here -->
        
                 <td >
                     <div style="width:99.5%" >
	      	         <table width="100%" border="0" cellspacing="0" cellpadding="0" id="subTabNavigation">
		      	      		<tr>
		      	      		   <td height="24" valign="bottom">
		      	      		     <table width="160" border="0" cellspacing="0" cellpadding="0">
		      	      		       <tr>
		      	      			      <td><ul><li class="selected marginB10"><a href="#" style="white-space:nowrap;" >
                                                         <%= i18n.tr("Email to Record Configuration") %>
                                                          </a><span></span></li></ul>
                                                          </td>
		      	      			   </tr>
	                             </table>
	                           </td>
	                        </tr>
							
                     </table>
                     </div>
               </td>
               
            <!-- Td to define the Top Tabs Ends here -->
         </tr>
        <tr>
               <td width="98%" align="center" valign="top">

		            <table width="100%" border="0" cellspacing="0" cellpadding="0">
		            
		                <tr>
		                
		                     <td>
		                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                <td valign="top" > 
                        <div class="contentBlock noMargin"> 
                        <div class="widgetOuterWrapper"> 
                        <div class="widgetInnerWrapper"> 
                  <table width="100%" border="0" cellspacing="0" cellpadding="0">
                 <%
                
                connection myConn = null;
				Connection conn   = null;
				PreparedStatement pstmt    = null;
				ResultSet rs      = null;
                String telantName= (String)session.getAttribute("TELANTNAME");
              
                String pop3server="";
	            String fromAddress="";
                    String maximumMailLimit = "5";
            	String smtpname="";
            	String smtppass="";
            	String MailDetails_ID="0";
				int pop3_port=110;
                int apopauth=0;
				String configuration ="";
				int selectedProject=0;
				int selectedService =-1;
				int selectedCategory=0;
				int selectedSubCategory=0;
				int selectedMode=0;
                int sslEnable=0;
                String strTransportType = "";
                String hideCheckBox = "none";
                int UrgencyID = 0;
                int ImpactID = 0;
                String isDomainFilter = "no";
                String isTitleCheckRequired = "0";
                String domainFilterValue ="";
                String hideDomainBox ="none";
                String hideInboxTab ="none";
                String folderList ="";
                String [] individualFolderName = null;
                String spamRule = "";
                String existingQueryRule = "";
                String spamRulePicSrc = "icon_plus.gif";
                String spamRuleDisplay = "none";
                String displayDeleteButton = "none";
                String emailCommandEnable = "";
                String emailCommandDisplay = "none";
                String emailEnableDisplay = "none";
                String emailCommandPicSrc = "icon_plus.gif";
                String emailCommandSubject = "";
                String emailCommandDelimiter = "";
                String PageType = "";
                String domLookUpDisplay = "none";
                String domLookUpPic = "icon_plus.gif";
                String domainLookupEnable = "";
                String domEnableDisplay = "none";
                int autoRecordSubmission=0;
                String sslDisplay = ""; 
                String portDisplay = ""; 
                String serverNameDisplay="";
                String providerDisplay="none";
                String userdetailblockD1 = "";
                String userdetailblockD2 = "";
                String userdetailblockD3 = "";
                String userdetailblockD4 = "none";
                String isAutoDiscoveryUsingUrl = "no";
                String discoveryUrlValue ="";
                String hideAutoDiscoveryUrlBox ="none";
                int providerId = 0;
                String hideAuthorizeAccess ="none";
                String returnQueryBuilderData = "";
                try
		{
                        myConn = new connection();
			conn = myConn.getConnection(telantName);
					
			if(request.getParameter("edit") != null){
				MailDetails_ID=request.getParameter("id");
                                PageType = "Edit";
				pstmt = conn.prepareStatement("SELECT ServerName, Port, UserName, Password, ApopAuthentication, FromMailAddress,Configuration,category,subCategory,mode,ServiceID,ProjectID,SSLEnabled,TransportType,UrgencyID,ImpactID,IsDomainFilter,DomainFilterValue, FolderList, SpamRule, QueryRule,EmailCommandEnable, EmailCommandSubject, EmailCommandDelimiter,DomainLookupEnable,AutoSubmissionEnable,MaxMailSize,mailProfileId,isTitleCheckRequired,isAutoDiscoveryUrl,autoDiscoveryUrlValue from mailserverdetails where MailDetailsID=? ");
			        pstmt.setString(1, MailDetails_ID);
                                rs = pstmt.executeQuery();
				      while(rs.next())
				        {
				    	pop3server=rs.getString(1);
					pop3_port=rs.getInt(2);
				    	smtpname=rs.getString(3);
				    	smtppass=rs.getString(4);
                                        smtppass=EncryptionUtil.decrypt(Sapphire.getAesPath(telantName),smtppass);
                                        apopauth=rs.getInt(5);
                                        fromAddress=rs.getString(6);
                                        configuration=rs.getString(7);						
                                        selectedCategory=rs.getInt(8);
                                        selectedSubCategory=rs.getInt(9);
                                        selectedMode=rs.getInt(10);						
                                        selectedService=rs.getInt(11);
                                        selectedProject=rs.getInt(12);
                                        sslEnable=rs.getInt(13);
                                        strTransportType = rs.getString(14);
                                        UrgencyID = rs.getInt(15);
                                        ImpactID =rs.getInt(16);
                                        isDomainFilter = rs.getString(17);
                                        domainFilterValue = rs.getString(18);
                                        folderList = rs.getString(19);
                                        spamRule = rs.getString(20);
                                        existingQueryRule = rs.getString(21);
                                        emailCommandEnable = rs.getString(22);
                                        emailCommandSubject = rs.getString(23);
                                        emailCommandDelimiter = rs.getString(24);
                                        domainLookupEnable = rs.getString(25);
                                        autoRecordSubmission = rs.getInt(26);
                                        maximumMailLimit = rs.getString(27);
                                        providerId = rs.getInt(28);
                                        isTitleCheckRequired = rs.getString(29);
                                        isAutoDiscoveryUsingUrl = rs.getString(30);
                                        discoveryUrlValue = rs.getString(31);
                                        existingQueryRule = existingQueryRule.replace("\"","&quot;");
                                        displayDeleteButton = "";
                                            spamRulePicSrc = "icon_plus.gif";
                                            spamRuleDisplay = "none";
                                        returnQueryBuilderData = rs.getString(21).replace("\"", "'");
                                        if(emailCommandEnable.equals("1"))
                                        {
                                            emailCommandDisplay = "";
                                            emailEnableDisplay = "";
                                            emailCommandPicSrc = "icon_minus.gif";
                                        }
                                        if( domainLookupEnable.equals("1") )
                                        {
                                            domLookUpPic = "icon_minus.gif";
                                            domLookUpDisplay = "";
                                            domEnableDisplay = "";
                                        }
                                        else
                                        {
                                            domLookUpPic = "icon_plus.gif";
                                            domLookUpDisplay = "none";
                                            domEnableDisplay = "none";
                                        }
                                    }
				    rs.close();
                                    pstmt.close();
                                    // Code is used to check the TransportType is Exchange while editing
                                    if( strTransportType.equals("Exchange")){
                                        sslDisplay = "none";
                                        portDisplay = "none";
                                        serverNameDisplay = "none";
                                        userdetailblockD4 = "";
                                    }
                                    if( strTransportType.equals("ModernAuth")){
                                        sslDisplay = "none";
                                        portDisplay = "none";
                                        serverNameDisplay = "none";
                                        providerDisplay="";
                                        userdetailblockD1 = "";
                                        userdetailblockD2 = "";
                                        userdetailblockD3 = "none";
                                    }
                                    if(strTransportType.equals("ModernIMAP")){
                                        sslDisplay = "";
                                        portDisplay = "";
                                        serverNameDisplay = "";
                                        providerDisplay="";
                                        userdetailblockD1 = "";
                                        userdetailblockD2 = "";
                                        userdetailblockD3 = "none";
                                    }
                                    //                                    
                            }
                %>
                       <tr>

					      <td align="right"  class="formtext"  width="20%"><%= i18n.tr("Configuration Name") %><span style="color:#ff0000">*</span></td>
					      <td  height="35" class="formfield" width="80%"> 
					      <input id="configuration" name="configuration"  type="text" class="mcopy" size="36" value="<%=configuration%>">
                                              &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('mainNote')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16"></span>
                                              </td>

                         </tr>
                         <tr>
                             <td height='25' class='copyhdr leftPadd' colspan='2'>Email Configuration Server Settings</td>
                         </tr>
                         <tr id="serverName" style="display:<%= serverNameDisplay %>">

					      <td align="right"  class="formtext"  width="20%"><%= i18n.tr("Server Name") %><span style="color:#ff0000">*</span></td>
					      <td  height="35" class="formfield" width="80%"> 
					      <input id="pop3server" name="pop3server"  type="text" class="mcopy" size="36" value="<%=pop3server%>"></td>

                         </tr>
                         <% if(strTransportType.equalsIgnoreCase("POP3")||strTransportType.equalsIgnoreCase("")){%>
			<tr>
                                  <td width="20%" class="formtext"><%= i18n.tr("Transport") %></td>
                                  <td class="formfield" ><input type="radio" id="Transport1" name="Transport" value="pop3" checked onclick="showApop()">
                                      <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">POP3</span>
                                    <input type="radio" id="Transport2" name="Transport" value="imap" onclick="hideApop()">
                                    <label class="customRadCheck" for="Transport2"><span><span></span></span></label><span class="notifyLabel noTopMargin">IMAP</span>
                                    <input type="radio" id="Transport3" name="Transport" value="Exchange" onclick="showExchange()">
                                    <label class="customRadCheck" for="Transport3"><span><span></span></span></label><span class="notifyLabel noTopMargin">Exchange</span>
                                    <input type="radio" id="Transport4" name="Transport" value="ModernAuth" onclick="showModernAuth()">
                                    <label class="customRadCheck" for="Transport4"><span><span></span></span></label><span class="notifyLabel noTopMargin">Modern Exchange</span>
                                    <input type="radio" id="Transport5" name="Transport" value="ModernIMAP" onclick="showModernIMAP()">
                                    <label class="customRadCheck" for="Transport5"><span><span></span></span></label><span class="notifyLabel noTopMargin">Modern IMAP</span></td>
                        </tr>
                        <%}else if(strTransportType.equalsIgnoreCase("imap")){%>
                        <tr>
                                  <td width="20%" class="formtext"><%= i18n.tr("Transport") %></td>
                                  <td class="formfield" ><input type="radio" id="Transport1" name="Transport" value="pop3" onclick="showApop()">
                                      <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">POP3</span>
                                      <input type="radio" id="Transport2" name="Transport" value="imap" checked onclick="hideApop()">
                                      <label class="customRadCheck" for="Transport2"><span><span></span></span></label><span class="notifyLabel noTopMargin">IMAP</span>
                                  <input type="radio" id="Transport3" name="Transport" value="Exchange" onclick="showExchange()">
                                  <label class="customRadCheck" for="Transport3"><span><span></span></span></label><span class="notifyLabel noTopMargin">Exchange</span>
                                  <input type="radio" id="Transport4" name="Transport" value="ModernAuth" onclick="showModernAuth()">
                                  <label class="customRadCheck" for="Transport4"><span><span></span></span></label><span class="notifyLabel noTopMargin">Modern Exchange</span>
                                  <input type="radio" id="Transport5" name="Transport" value="ModernIMAP" onclick="showModernIMAP()">
                                  <label class="customRadCheck" for="Transport5"><span><span></span></span></label><span class="notifyLabel noTopMargin">Modern IMAP</span></td>
                      </tr>
                      <%}else if(strTransportType.equalsIgnoreCase("Exchange")){%>
                        <tr>
                                  <td width="20%" class="formtext"><%= i18n.tr("Transport") %></td>
                                  <td class="formfield" ><input type="radio" id="Transport1" name="Transport" value="pop3" onclick="showApop()">
                                      <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">POP3</span>
                                  <input type="radio" id="Transport2" name="Transport" value="imap"  onclick="hideApop()">
                                  <label class="customRadCheck" for="Transport2"><span><span></span></span></label><span class="notifyLabel noTopMargin">IMAP</span>
                                  <input type="radio" id="Transport3" name="Transport" value="Exchange" checked onclick="showExchange()">
                                  <label class="customRadCheck" for="Transport3"><span><span></span></span></label><span class="notifyLabel noTopMargin">Exchange</span>
                                  <input type="radio" id="Transport4" name="Transport" value="ModernAuth" onclick="showModernAuth()">
                                  <label class="customRadCheck" for="Transport4"><span><span></span></span></label><span class="notifyLabel noTopMargin">Modern Exchange</span>
                                  <input type="radio" id="Transport5" name="Transport" value="ModernIMAP" onclick="showModernIMAP()">
                                  <label class="customRadCheck" for="Transport5"><span><span></span></span></label><span class="notifyLabel noTopMargin">Modern IMAP</span></td>
                      </tr>
                      <%} else if(strTransportType.equalsIgnoreCase("ModernAuth")){%>
                        <tr>
                                  <td width="20%" class="formtext">Transport</td>
                                  <td class="formfield" ><input type="radio" id="Transport1" name="Transport" value="pop3" onclick="showApop()">
                                  <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">POP3</span>
                                  <input type="radio" id="Transport2" name="Transport" value="imap"  onclick="hideApop()">
                                  <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">IMAP</span>
                                  <input type="radio" id="Transport3" name="Transport" value="Exchange" onclick="showExchange()">
                                  <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">Exchange</span>
                                  <input type="radio" id="Transport4" name="Transport" value="ModernAuth" checked onclick="showModernAuth()">
                                  <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">Modern Exchange</span>
                                  <input type="radio" id="Transport5" name="Transport" value="ModernIMAP" onclick="showModernIMAP()">
                                  <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">Modern IMAP</span></td>
                      </tr>
                      <% } else {%>
                        <tr>
                                  <td width="20%" class="formtext"><%= i18n.tr("Transport") %></td>
                                  <td class="formfield" ><input type="radio" id="Transport1" name="Transport" value="pop3" onclick="showApop()">
                                  <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">POP3</span>
                                  <input type="radio" id="Transport2" name="Transport" value="imap"  onclick="hideApop()">
                                  <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">IMAP</span>
                                  <input type="radio" id="Transport3" name="Transport" value="Exchange" onclick="showExchange()">
                                  <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">Exchange</span>
                                  <input type="radio" id="Transport4" name="Transport" value="ModernAuth"  onclick="showModernAuth()">
                                  <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">Modern Exchange</span>
                                  <input type="radio" id="Transport5" name="Transport" value="ModernIMAP" checked onclick="showModernIMAP()">
                                  <label class="customRadCheck" for="Transport1"><span><span></span></span></label><span class="notifyLabel noTopMargin">Modern IMAP</span></td>
                      </tr>
                      <% } %>
                      <%if(strTransportType.equalsIgnoreCase("POP3")||strTransportType.equalsIgnoreCase("")){
                          hideCheckBox = "";
                      }
					      if(apopauth==1){%>
                                         <tr id="apopRow" style="display :<%=hideCheckBox%>">
					      <td bgcolor="#FFFFFF" class="formtext" width="20%">APOP <%= i18n.tr("Authentication") %></td>
					      <td  height="35"  class="formfield" width="5%"><input id="popauth" name="popauth"  type="checkbox" class="mcopy" size="36" value="1" checked>
                                                   <label class="customRadCheck" for="popauth"><span><span></span></span></label>
                                                  &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('apopNote')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16"></span>
                                              </td>
                                        </tr> 
						  <%}else{
						  %>
					<tr id="apopRow" style="display :<%=hideCheckBox%>"> 
					      <td  bgcolor="#FFFFFF" class="formtext"  width="20%">APOP <%= i18n.tr("Authentication") %></td>
					      <td  height="35"  bgcolor="#FFFFFF" class="formfield" width="5%"><input id="popauth" name="popauth"  type="checkbox" class="mcopy" size="36" value="1" >
                                                  <label class="customRadCheck" for="popauth"><span><span></span></span></label>
                                              &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('apopNote')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16"></span>
                                              </td>
                                       </tr> 
					  <%}
                                             %>
                            <tr id="sslRow" style="display:<%= sslDisplay %>">
                                <td align="right" bgcolor="#FFFFFF" class="formtext"  width="20%"><%= i18n.tr("Use") %> SSL</td>
                                <td  height="35" bgcolor="#FFFFFF" class="formfield" width="80%"> 
                                <% if(sslEnable==1){ %>    
                                <input id="sslenable" name="sslenable"  type="checkbox" size="36" class="mcopy" value="1" checked onclick="changePortNumber()">
                                <label class="customRadCheck" for="sslenable"><span><span></span></span></label>
                                &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('sslNotes')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16"></span></td>
                                <% } else { %>
                                  <input id="sslenable" name="sslenable"  type="checkbox" size="36" class="mcopy" value="0" onclick="changePortNumber()">
                                  <label class="customRadCheck" for="sslenable"><span><span></span></span></label>
                                  &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('sslNotes')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16"></span></td>
                                <% } %>
                           </tr>
                           <%
                                if(strTransportType.equalsIgnoreCase("POP3")){
                                    if(sslEnable==1){
                                        pop3_port = 995;
                                    }
                                    else{
                                        pop3_port = 110;
                                    } 
                                }
                                else if(strTransportType.equalsIgnoreCase("IMAP")){
                                    if(sslEnable==1){
                                        pop3_port = 993;
                                    }
                                    else{
                                        pop3_port = 143;
                                    } 
                                }
                                else if(strTransportType.equalsIgnoreCase("ModernIMAP")){
                                    if(sslEnable==1){
                                        pop3_port = 993;
                                    }
                                    else{
                                        pop3_port = 143;
                                    } 
                                }
                           
                           %>
                         <tr id='portRow' style="display:<%= portDisplay %>">
					      <td align="right" bgcolor="#FFFFFF" class="formtext"  width="20%"><%= i18n.tr("Port Number") %><span style="color:#ff0000">*</span></td>
					      <td  height="35" bgcolor="#FFFFFF" class="formfield" width="80%"> 
					      <input id="pop3port" name="pop3port"  type="text" class="mcopy" size="36" value="<%=pop3_port%>">

						</td>

		          </tr>
                          <tr id='providerRow' style="display:<%= providerDisplay %>">
                                <td align="right" bgcolor="#FFFFFF" width="20%" class="formtext"><%= i18n.tr("Mail Profile") %><span style="color:#ff0000">*</span> </td>
                                <td width="80%" height="35" bgcolor="#FFFFFF" class="formfield">
                                    <%int mailSelectedProfile = 0;%>
                                    <select id="provider" name="provider" class="mcopy" style="width:180px" onchange="clearTokenDetails()">
                                        <option value="" selected ><%= i18n.tr("---- choose ----") %></option>
                                            <%
                                                String typeMailProfile = "1,2";//Modern IMAP
                                                if(strTransportType.equalsIgnoreCase("ModernAuth")){
                                                    typeMailProfile = "3";
                                                }
                                                pstmt = conn.prepareStatement("select sno, profileName from mailprofiles where type in  ("+typeMailProfile+")");
                                                rs=pstmt.executeQuery();
                                                while(rs.next()){
                                                    if(providerId ==  rs.getInt(1)){
                                                        mailSelectedProfile = providerId;
                                                            %>
                                                          <option value="<%=rs.getString(1)%>" selected><%=rs.getString(2)%></option>
                                                            <%

                                                    }else{
                                                            %>
                                                          <option value="<%=rs.getString(1)%>"><%=rs.getString(2)%></option>
                                                            <%
                                                    }
                                                }
                                                rs.close();
                                                pstmt.close();
                                            %>		   
                                    </select>
                                    <input type="hidden" id="providerSelected" value="<%=mailSelectedProfile%>"/>
                                </td>
                            </tr>
				  </table>
                                    
                                <div id="userdetailblock4" style="display:<%= userdetailblockD4 %>">
                                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                          <%if(isAutoDiscoveryUsingUrl.equalsIgnoreCase("no")||isAutoDiscoveryUsingUrl.equalsIgnoreCase("")){%>
                                          <tr>
                                              <td width="20%" class="formtext">Discovery Type </td>
                                              <td class="formfield wid100" ><input type="radio" id="autoDiscoveryUrl1" name="autoDiscoveryUrl" value="yes" onclick="showAutodiscoveryUrlBox()"><label class="customRadCheck" for="autoDiscoveryUrl1"><span><span></span></span></label><span class=notifyLabel>URL</span>
                                              <input type="radio" id="autoDiscoveryUrl2" name="autoDiscoveryUrl" value="no" checked onclick="showAutodiscoveryUrlBox()"><label class="customRadCheck" for="autoDiscoveryUrl2"><span><span></span></span></label><span class=notifyLabel>Auto-Discovery</span></td>
                                           </tr>
                                          <%}else{
                                             hideAutoDiscoveryUrlBox=""; %>
                                           <tr>
                                              <td width="20%" class="formtext">Discovery Type </td>
                                              <td class="formfield"><input type="radio" id="autoDiscoveryUrl1" name="autoDiscoveryUrl" value="yes" checked onclick="showAutodiscoveryUrlBox()">URL
                                              <input type="radio" id="autoDiscoveryUrl2" name="autoDiscoveryUrl" value="no" onclick="showAutodiscoveryUrlBox()"><label class="customRadCheck" for="autoDiscoveryUrl2"><span><span></span></span></label><span class=notifyLabel>Auto-Discovery</span></td>
                                           </tr>
                                           <%}%>
                                    </table>
                                    <table width="100%" border="0" cellspacing="0" cellpadding="0" colspan="2">
                                        <tr  id="autoDiscoveryUrlDiv" style="display :<%=hideAutoDiscoveryUrlBox%>" >
                                             <td align="right"  class="formtext wid100"  width="20%">Auto-Discovery URL<span style="color:#ff0000">*</span></td>
                                             <td  height="35" class="formfield wid100" ><input id="discoveryUrlValue" name="discoveryUrlValue"  type="text" class="mcopy" size="36" value="<%=discoveryUrlValue%>">
                                             &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('autoDiscoveryUrlNote')" onmouseout="tooltip.hide();"><img style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16"></span>
                                             </td>
                                        </tr> 
                                    </table>
                      
                                </div>
                                    
                      
   					<table width="100%" border="0" cellspacing="0" cellpadding="0">
				      		
                                        
					 
					
					   <tr id="userdetailblock" style="display:<%= userdetailblockD1 %>">
							      <td  bgcolor="#FFFFFF" class="formtext"  width="20%"><%= i18n.tr("Polling Email Id") %><span style="color:#ff0000">*</span></td>
							      <td  height="35" bgcolor="#FFFFFF" class="formfield" width="80%"> 
							      <input id="fromEmailAddres" name="fromEmailAddres"  type="text" class="mcopy" size="36" value="<%=fromAddress%>">
                                                              <div id="showProcessMsg" style="display:none" align="right" class="mcopy">
						<img alt="Indicator" src="<%=request.getContextPath()%>/img/indicator.gif" /> Processing...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						</div>
							      </td>
				      </tr>
					  <tr id="userdetailblock2" style="display:<%= userdetailblockD2 %>">
							      <td  bgcolor="#FFFFFF" class="formtext"  width="20%"><%= i18n.tr("User Name") %><span style="color:#ff0000">*</span></td>
							      <td  height="35" bgcolor="#FFFFFF" class="formfield" width="80%"> 
                                        <%  String userMouseOver = "display:none";
                                            if(strTransportType.equalsIgnoreCase("ModernIMAP")||strTransportType.equalsIgnoreCase("ModernAuth")){
                                            userMouseOver = "";
                                        %>
							    <input id="user" name="user"  type="text" class="mcopy" size="36" readonly value="<%=smtpname%>">                                                            
                                        <%}else{%>
                                                            <input id="user" name="user"  type="text" class="mcopy" size="36" value="<%=smtpname%>">
                                        <%}%>
                                        &nbsp;&nbsp;<span style="<%=userMouseOver%>" id="userMouseOverId" class="hotspot" onmouseover="mouseOverMessage('userModerAuth')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16"></span>
                                        
                                                              </td>
				      </tr>
                                      <% if(strTransportType.equalsIgnoreCase("ModernIMAP")||strTransportType.equalsIgnoreCase("ModernAuth")){
                                         hideAuthorizeAccess = "";
                                     }%>
                                       <tr id="authorizeAccessDiv" style="display: <%=hideAuthorizeAccess%>">
                                           <td align="right"  class="formtext"  width="20%"></td>
                                            <td  height="35" class="formfield autoHt wid100 negativeMargin" >
                                               <input id="scanBtn"  type="button"  onClick="authAccess()"  value="Authorize Access"  class="addbuttons greenBtn floatRightAsset negativeMargin" />
                                               <input type="hidden" id="accessToken" name="accessToken" value=""/>
                                               <input type="hidden" id="expiresIn" name="expiresIn" value=""/>
                                               <input type="hidden" id="refreshToken" name="refreshToken" value=""/>
                                               <input type="hidden" id="expiryDate" name="expiryDate" value=""/>
                                           </td>
                                       </tr>
		
				       <tr id="userdetailblock3" style="display:<%= userdetailblockD3 %>">
							      <td  align="right" bgcolor="#FFFFFF" class="formtext"  width="20%"><%= i18n.tr("Password") %><span style="color:#ff0000">*</span></td>
							      <td  height="35" bgcolor="#FFFFFF" class="formfield" width="80%"> 
							      <input id="pass" name="pass"  type="password" autocomplete="off" class="mcopy" size="36" value="">
							      </td>
				      </tr>
                                      <tr>
							      <td  align="right" bgcolor="#FFFFFF" class="formtext"  width="20%"><%= i18n.tr("Maximum Message Size") %> (MB)<span style="color:#ff0000">*</span></td>
							      <td  height="35" bgcolor="#FFFFFF" class="formfield" width="80%"> 
                                                                  <input id="messagelimit" name="messagelimit"  type="number" min="0" max="100" class="mcopy" size="36" value="<%=maximumMailLimit%>" />
                                                                  &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('messagelimit')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16"></span>
							      </td>
                                                              
				      </tr>
                            <% if (isTitleCheckRequired.equalsIgnoreCase("0") || isTitleCheckRequired.equalsIgnoreCase("")) {%>
                            <tr>
                                <td width="20%" class="formtext">Title Check Required?</td>
                                <td class="formfield"><input type="radio" id="titleCheck1" name="titleCheck" value="1"><label class="customRadCheck" for="titleCheck1"><span><span></span></span></label><span class="notifyLabel noTopMargin">Yes</span>
                                    <input type="radio" id="titleCheck2" name="titleCheck" value="0" checked><label class="customRadCheck" for="titleCheck2"><span><span></span></span></label><span class="notifyLabel noTopMargin">No</span>
                                </td>
                            </tr>
                            <% } else { %>
                            <tr>
                                <td width="20%" class="formtext">Title Check Required?</td>
                                <td class="formfield"><input type="radio" id="titleCheck1" name="titleCheck" value="1" checked><label class="customRadCheck" for="titleCheck1"><span><span></span></span></label><span class="notifyLabel noTopMargin">Yes</span>
                                    <input type="radio" id="titleCheck2" name="titleCheck" value="0"><label class="customRadCheck" for="titleCheck2"><span><span></span></span></label><span class="notifyLabel noTopMargin">No</span>
                                </td>
                            </tr>
                            <%}%>
                              <% if(isDomainFilter.equalsIgnoreCase("no")||isDomainFilter.equalsIgnoreCase("")){%>
                              <tr>
                                  <td width="20%" class="formtext">Domain Filter Required?</td>
                                  <td class="formfield" ><input type="radio" id="domainFilter1" name="domainFilter" value="yes" onclick="showDomainBox()">
                                  <label class="customRadCheck" for="domainFilter1"><span><span></span></span></label><span class="notifyLabel noTopMargin">Yes</span>
                                  <input type="radio" id="domainFilter2" name="domainFilter" value="no" checked onclick="showDomainBox()">
                                  <label class="customRadCheck" for="domainFilter2"><span><span></span></span></label><span class="notifyLabel noTopMargin">No</span></td>
                               </tr>
                              <%}else{
                                 hideDomainBox=""; %>
                               <tr>
                                  <td width="20%" class="formtext">Domain Filter Required?</td>
                                  <td class="formfield"><input type="radio" id="domainFilter1" name="domainFilter" value="yes" checked onclick="showDomainBox()">
                                    <label class="customRadCheck" for="domainFilter1"><span><span></span></span></label><span class="notifyLabel noTopMargin">Yes</span>
                                  <input type="radio" id="domainFilter2" name="domainFilter" value="no" onclick="showDomainBox()">
                                  <label class="customRadCheck" for="domainFilter2"><span><span></span></span></label><span class="notifyLabel noTopMargin">No</span></td>
                               </tr>
                               <%}%>
                               </table>
                               <table width="100%" border="0" cellspacing="0" cellpadding="0" colspan="2">
                                <tr  id="filterDiv" style="display :<%=hideDomainBox%>" >
                                     <td align="right"  class="formtext"  width="20%"><%= i18n.tr("Domain Filter") %><span style="color:#ff0000">*</span></td>
                                     <td  height="35" class="formfield" ><input id="filterValue" name="filterValue"  type="text" class="mcopy" size="36" value="<%=domainFilterValue%>">
                                     &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('domainFilterNote')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16" ></span>
                                     </td>
                                 </tr> 
                                </table>
                                     <table width="100%" border="0" cellspacing="0" cellpadding="3">
                            <tr>
                               <td height='25' class='copyhdr' colspan='2'>
                                 <span onclick="showemailcomdiv()" style="cursor: pointer">
                                    <img id="emailComPic" border="0" name="emailComPic" title="Show Email Command Rules" src="<%=emailCommandPicSrc%>?<%=new Date().getTime()%>">
                                 </span><span class="topMargin5">Email Command Rules</span>
                               </td>
                            </tr>
                           </table>
                            <table id="emailEnableTr" width="100%" border="0" cellspacing="0" cellpadding="0" style="display: <%=emailEnableDisplay%>">                                     
                               <tr>
                                    <td bgcolor="#FFFFFF" class="formtext" width="20%"><%= i18n.tr("Enable Email Command") %></td>
                                    <td  height="35"  class="formfield" >
                                        <% if(emailCommandEnable.equals("1")){%> 
                                        <input id="emailcom" name="emailcom"  type="checkbox" class="mcopy" size="36" value="1" checked onclick="displayemailcomDiv()">
                                        <label class="customRadCheck" for="emailcom"><span><span></span></span></label>
                                        <%}else{%>
                                        <input id="emailcom" name="emailcom"  type="checkbox" class="mcopy" size="36" value="0" onclick="displayemailcomDiv()">
                                        <label class="customRadCheck" for="emailcom"><span><span></span></span></label>
                                        <%}%>
                                      &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('enableCommand')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16"></span>
                                      &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('emailTemplate')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16"></span>
                                    </td>
                               </tr> 
                            </table>
                            <div id="emailcomDiv" style="display: <%=emailCommandDisplay%>"> 
                                <table width="100%" border="0" cellspacing="0" cellpadding="0">                                     
                                   <tr>
                                       <td bgcolor="#FFFFFF" class="formtext" width="20%"><%= i18n.tr("Email Subject Filter") %><span style="color:#ff0000">*</span></td>
                                       <td  height="35" class="formfield wid100"><input id="emailsub" name="emailsub"  type="text" class="mcopy" size="36" value="<%=emailCommandSubject%>">
                                       &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('subjectLine')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16" ></span>
                                       </td>
                                   </tr>
                                   <tr>
                                       <td bgcolor="#FFFFFF" class="formtext" width="20%"><%= i18n.tr("Email Command Delimiter") %><span style="color:#ff0000">*</span></td>
                                       <td  height="35" class="formfield wid100"><input id="emaildel" name="emaildel"  type="text" class="mcopy" size="36" value="<%=emailCommandDelimiter%>">
                                       &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('delimiter')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16"></span>
                                       </td>
                                   </tr>
                               </table>
                           </div>
                             
                        
                         <% if(strTransportType.equalsIgnoreCase("IMAP") || strTransportType.equalsIgnoreCase("ModernIMAP")){
                             hideInboxTab = "";
                         }%>
                         <div id="inboxDiv" style="display: <%=hideInboxTab%>">
                            <table width="100%" border="0" cellspacing="0" cellpadding="0" >
                               <tr>
                                   <td height='25' class='copyhdr leftPadd' colspan='2'>Email Inbox Folders </td>
                               </tr> 
                            </table>
                            <table width="100%" border="0" cellspacing="0" cellpadding="0" >
                               <tr>
                                   <td align="right"  class="formtext"  width="20%"><%= i18n.tr("Mail Folders") %></td>
                                   <td  height="35" class="formfield wid100" >
                                       <select id="folderslist" name="folderslist" class="gen" multiple="multiple" size="7" style="width:280px">
                                           <%
                                               individualFolderName = folderList.split(",");
                                               for(int i = 0; i < individualFolderName.length; i++) {
                                                   String folder = individualFolderName[i].trim();
                                                   if (!folder.equals("")) {
                                           %>
                                           <option value="<%= folder %>" title="<%= folder %>" selected>
                                               <%= folder %>
                                           </option>
                                           <%
                                                   }
                                               }
                                           %>
                                       </select>
                                   </td>
                                    <td  height="35" class="formfield floatRightAsset negativeMargin" >
                                       <input id="scanBtn"  type="button"  onClick="scanMailbox()"  value="Scan Mailbox"  class="addbuttons greenBtn negativeMargin" />
                                       &nbsp;&nbsp;<span class="hotspot  floatRight negativeMargin noRightMargin avoidTooltipCollision" onmouseover="mouseOverMessage('mailBoxNote')" onmouseout="tooltip.hide();" style="margin-right: 550px;"><img class="topMargin30 floatRight" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16" ></span>
                                   </td>
                               </tr>
                            </table>
                         </div>
                         <br class="hiddenDisplay"/>
                         <table width="100%" border="0" cellspacing="0" cellpadding="3">
                            <tr>
                               <td height='25' class='copyhdr' colspan='2'>
                                 <span onclick="showhidepane()" style="cursor: pointer">
                                    <img id="PlusMinusImg" border="0" name="PlusMinusImg" title="Show Spam Filtering Rules" src="<%=spamRulePicSrc%>?<%=new Date().getTime()%>">
                                 </span><span class="topMargin5">Spam Filter Rules</span>
                               </td>
                            </tr>
                  </table>
                                 <div id="builder" style="display: <%=spamRuleDisplay%>"></div>
                                  <input type="hidden" id="existingRule" name="existingRule" value="<%=spamRule%>"/>
                                <input type="hidden" id="returnQueryBuilderData" name="returnQueryBuilderData" value="<%=returnQueryBuilderData%>">
                         <br class="hiddenDisplay"/>
                         <table width="100%" border="0" cellspacing="0" cellpadding="3">
                            <tr>
                               <td height='25' class='copyhdr' colspan='2'>
                                 <span onclick="showlookuppane()" style="cursor: pointer">
                                    <img id="DomLookUpImg" border="0" name="DomLookUpImg" title="Show Domain Lookup Options" src="<%=domLookUpPic%>?<%=new Date().getTime()%>">
                                 </span><span class="topMargin5">Domain Lookup</span>
                               </td>
                            </tr>
                  </table>
                                 <table id="domLookupTr" width="100%" border="0" cellspacing="0" cellpadding="0" style="display: <%=domEnableDisplay%>">                                     
                               <tr>
                                    <td bgcolor="#FFFFFF" class="formtext" width="20%"><%= i18n.tr("Enable Domain Lookup") %></td>
                                    <td  height="35"  class="formfield" >
                                        <% if(domainLookupEnable.equals("1")){%> 
                                        <input id="domlook" name="domlook"  type="checkbox" class="mcopy" size="36" value="1" checked onclick="displaydomlookup()">
                                        <label class="customRadCheck" for="domlook"><span><span></span></span></label>
                                        <%}else{%>
                                        <input id="domlook" name="domlook"  type="checkbox" class="mcopy" size="36" value="0" onclick="displaydomlookup()">
                                        <label class="customRadCheck" for="domlook"><span><span></span></span></label>
                                        <%}%>
                                    </td>
                               </tr> 
                            </table>
                                    <div id="lookupDiv"  style="display: <%=domLookUpDisplay%>">
                               <table  width="100%" border="0" cellspacing="0" cellpadding="0">                                     
                                   <tr >
                                       <td bgcolor="#FFFFFF" class="formtext" width="20%"><%= i18n.tr("Domain Name") %><span style="color:#ff0000">*</span></td>
                                       <td  align="left" bgcolor="#FFFFFF" class="formfield wid100">
                                           <input type="text" id="domainName" name="domainName" class="mcopy" size="43">
                                       </td>
                                   </tr>
                               </table>
                               <table  width="100%" border="0" cellspacing="0" cellpadding="0">                                     
                                   <tr>
                                       <td bgcolor="#FFFFFF" class="formtext" width="20%"><%= i18n.tr("Users") %><span style="color:#ff0000">*</span></td>
                                       <td class="formfield wid100">
                                            <div id="users1" name="users1">
                                            </div>
                                           <td bgcolor="#FFFFFF" class="formtext">
                                               <input id="addDomButton"  type="button"  name="addDomButton" onClick="addDomain()" value="Add"  class="addbuttons greenBtn floatRightAsset negativeMargin noRightMargin" style="margin-right: 675px;"/>
                                           </td>
                                           <input class="mcopy" type="hidden" id="users" name="users" value=""/>
                                            <input class="mcopy" type="hidden" id="username" name="username" value=""/>
                                       </td>
                                   </tr>
                               </table>
                               <table  width="100%" border="0" cellspacing="0" cellpadding="0">
                                   <tr>
                                        <td colspan="2">
                                            <table width="100%">
                                                <tr  class="disk autoHt">
                                                    <td width="10%" align="center"></td>
                                                    <td width="45%" align="center"><%= i18n.tr("Domain Name") %></td>
                                                    <td width="45%" align="center"><%= i18n.tr("Username") %></td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                               </table>
                               <div id="dynamicRow_Domain">
                                    <%
                                        int rowCount = 0;
                                        String userValues = "";
                                        String domainValues = "";
                                        int sNo = 0;
                                        pstmt = conn.prepareStatement("Select Lookupname, lookupvalue, fullname,userid,sdl.sno from sd_emailticket_lookup sdl inner join usermgmt_master on lookupvalue=userid where maildetailsid = ?");
                                        pstmt.setString(1,MailDetails_ID);
                                        rs = pstmt.executeQuery();
                                        while(rs.next())
                                        {
                                            
                                            rowCount++;
                                            sNo = rs.getInt(5);
                                            String divIdName="Div_"+rowCount+"_Domain";
                                            if( userValues.isEmpty() )
                                            {
                                                userValues = rs.getString(4);
                                            }
                                            else
                                            {
                                                userValues += ","+rs.getString(4);
                                            }
                                            if( domainValues.isEmpty() )
                                            {
                                                domainValues = rs.getString(1);
                                            }
                                            else
                                            {
                                                domainValues += ","+rs.getString(1);
                                            }
                                    %>
                                    <div id="<%=divIdName%>" >
                                        <table width="100%" border="0" class="ruleList">
                                                    <tr>
                                        <td colspan="2" class="wid100">
                                            <table width="100%">
                                                <tr  class="formfield ruleList">
                                                    <td class="formfield" width="10%" align="center">
                                                <a href="javascript:;" class="delete1" title="Delete" onclick="removeDom('<%=divIdName%>','<%=sNo%>')"><img border="0" src="fault_x.gif" width="12" height="12" class="deleteRule"></a>
                                            </td>
                                            <td bgcolor="#FFFFFF" width="45%" align="center" class="formfield" ><%=rs.getString(1)%></td>
                                            <td bgcolor="#FFFFFF" width="45%" align="center" class="formfield" ><%=rs.getString(3)%></td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                                  </table>
                                    </div>
                                   <%}%>
                                   <input type="hidden" id="globalUserID" name="globalUserID" value="<%=userValues%>"/>
                                   <input type="hidden" id="globalDomName" name="globalDomName" value="<%=domainValues%>"/>
                                   <input type="hidden"  id="accessrowcount" name="accessrowcount" value="<%= rowCount %>">
                                   <input type="hidden"  id="addflag" name="addflag" value="0">
                                   <input type="hidden"  id="deleted_sno" name="deleted_sno" value="">
                                   </div>
                                    </div>
                         <br class="hiddenDisplay"/>
                         <table width="100%" border="0" cellspacing="0" cellpadding="0">
                            
			 <tr>
                             <td height='25' class='copyhdr leftPadd' colspan='2'>Email Configuration Project Settings</td>
                         </tr>  
                         <% if( autoRecordSubmission == 0 ){%>
                         <tr>
                             <td align="right" bgcolor="#FFFFFF" width="20%" class="formtext"><%= i18n.tr("Auto Record Submission") %></td>
                             <td width="80%" height="35" bgcolor="#FFFFFF" class="formfield">
                                  <input type="radio" id="autoSubmissionDisable" name="autoSubmission" value="0" checked /> 
                                  <label class="customRadCheck" for="autoSubmissionDisable"><span><span></span></span></label><span class="notifyLabel noTopMargin">Disable</span>
                                  <input type="radio" id="autoSubmissionEnable" name="autoSubmission" value="1"/>
                                  <label class="customRadCheck" for="autoSubmissionEnable"><span><span></span></span></label><span class="notifyLabel noTopMargin">Enable</span>
                                  &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('autoSubmissionNote')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16" ></span>
                             </td>
                         </tr>
                         <% } else { %>
                         <tr>
                             <td align="right" bgcolor="#FFFFFF" width="20%" class="formtext"><%= i18n.tr("Auto Record Submission") %></td>
                             <td width="80%" height="35" bgcolor="#FFFFFF" class="formfield">
                                  <input type="radio" id="autoSubmissionDisable" name="autoSubmission" value="0" />
                                  <label class="customRadCheck" for="configSettingValueNo"><span><span></span></span></label><span class="notifyLabel noTopMargin">Disable</span>
                                  <input type="radio" id="autoSubmissionEnable" name="autoSubmission" value="1" checked />
                                  <label class="customRadCheck" for="configSettingValueNo"><span><span></span></span></label><span class="notifyLabel noTopMargin">Enable</span>
                                  &nbsp;&nbsp;<span class="hotspot" onmouseover="mouseOverMessage('autoSubmissionNote')" onmouseout="tooltip.hide();"><img class="topMargin8" style="cursor:pointer;" src="help_small.gif" alt="Help" height="16" width="16" ></span>
                             </td>
                         </tr>
                         <% } %>
                        <tr>
                        <td align="right" bgcolor="#FFFFFF" width="20%" class="formtext">${applicationScope.SAPPHIRE_CONFIG_SETTINGS.findBySettingKey('SERVICEDESK_PROJECT_NAME')}<span style="color:#ff0000">*</span> </td>
                        <td width="80%" height="35" bgcolor="#FFFFFF" class="formfield">
                                                       
							<select id="project" name="project" class="mcopy" style="width:180px" onchange="changeproject()">
							 <option value="" selected ><%= i18n.tr("---- choose ----")%></option>
								<%
								 
                                                                                pstmt = conn.prepareStatement("select ProjectID, ProjectName from sd_project_master where Status=0");
								  		rs=pstmt.executeQuery();
								  	 
								  		while(rs.next()){
												
												if(selectedProject ==  rs.getInt(1)){
													%>
									                              <option value="<%=rs.getString(1)%>" selected><%=rs.getString(2)%></option>
													<%
												
												}else{
													%>
									                              <option value="<%=rs.getString(1)%>"><%=rs.getString(2)%></option>
													<%
												}														

								  		}
								  		rs.close();
                                                                                pstmt.close();
					  %>		   
							</select>
                      
                        </td>
                       </tr> 	
                      <tr>
                      <td colspan="2" class="wid100">
                      <div style="display: block">
                      <table width="100%" cellpadding="0" cellspacing="0">
                      <tr>
						 <td width="20%" class="formtext">Service<span style="color:#ff0000">*</span> </td>
				         
				         <td width="80%" align="left"  class="formfield">
	            
							<select id="ServiceLine" name="ServiceLine" class="mcopy" style="width:180px" onchange="changeService()">
							 <option value="" selected ><%= i18n.tr("---- choose ----") %></option>
							<%pstmt = conn.prepareStatement("SELECT ServiceID, ServiceName FROM sd_service where Status=0 and ProjectID=? order by ServiceName"); 
                                                        pstmt.setInt(1,selectedProject);
                                                          rs=pstmt.executeQuery();
							
						  	  while(rs.next())
					  	   	  { 					  	         
					  	          if(selectedService == rs.getInt(1)){%>
						             <option value="<%=rs.getInt(1)%>" selected="selected"><%=rs.getString(2)%></option>
						        <%}else{ %>
						             <option value="<%=rs.getInt(1)%>"><%=rs.getString(2)%></option>
						   <%     }
					   		 }rs.close();
                                                         pstmt.close();%>
							 
							</select>
							
						 </td>
					 </tr>
					 </table>
					 </div>
					 </td>
					 </tr>
					
                  
 
                      <tr>
                        <td align="right" bgcolor="#FFFFFF" width="20%" class="formtext"><%= i18n.tr("Category") %><span style="color:#ff0000">*</span></td>
                        <td width="80%" height="35" bgcolor="#FFFFFF" class="formfield">
                       		<select id="category" name="category" class="mcopy" style="width:180px" onchange="changeCategory()">  
							 
							    <option value="" selected ><%= i18n.tr("---- choose ----") %></option>
							 
								<%
					 			   	pstmt = conn.prepareStatement("select sc.CategoryId,sc.CategoryName from sd_categorymaster sc inner join sd_service_parameters_details sspd on sc.CategoryId = sspd.ParameterValue where sspd.ParameterID=1 and (sspd.ServiceID=? or sspd.ServiceID=0) and sc.Status=0 and sc.ProjectID=? order by sc.CategoryName");
									pstmt.setInt(1,selectedService);
                                                                        pstmt.setInt(2,selectedProject);
                                                                        rs=pstmt.executeQuery();
							  				while(rs.next()){
 									 	if(selectedCategory ==  rs.getInt(1)){												  
													%>
									                              <option value="<%=rs.getInt(1)%>" selected><%=rs.getString(2)%></option>
													<%
											 	}else{
													%>
									                              <option value="<%=rs.getInt(1)%>"><%=rs.getString(2)%></option>
													<%
												}														
												
								  		}
								  		rs.close();
                                                                                pstmt.close();%>		
								 					
							
							</select>
                                <select class="ServiceDummyDiv1" id="ServiceDummyDiv1" style="width:250px;display:none;">
                                            <option value="0"><%= i18n.tr("------choose------") %></option>
                                </select>
                                 <select class="ServiceDummyDiv2" id="ServiceDummyDiv2" style="width:250px;display:none;">
                                            <option value="0"><%= i18n.tr("------choose------") %></option>
                                </select>
                                <select class="ServiceDummyDiv3" id="ServiceDummyDiv3" style="width:250px;display:none;">
                                            <option value="0"><%= i18n.tr("------choose------")%></option>
                                </select>
                                
                                                                                
                        </td>
                       </tr> 
 
                      <tr>
                        <td align="right" bgcolor="#FFFFFF" width="20%" class="formtext"><%= i18n.tr("Sub Category") %></td>
                        <td width="80%" height="35" bgcolor="#FFFFFF" class="formfield">
                            <input type="hidden" id="loggedInUserID" name="loggedInUserID" value="<%=(String)session.getAttribute("LOGGEDUSERID")%>"/>
                          	<select id="subCategoryId" name="subCategoryId" class="mcopy" style="width:180px" >
							      <option value="" selected><%= i18n.tr("---- choose ----") %></option>
								<%
								   		pstmt = conn.prepareStatement("select SubCategoryId,SubCategoryName from sd_subcategorymaster where CategoryID=? and Status=0 and ProjectID=? order by SubCategoryName" );
                                                                                pstmt.setInt(1,selectedCategory);
                                                                                 pstmt.setInt(2,selectedProject);
                                                                                rs=pstmt.executeQuery();
								  		while(rs.next()){

												if(selectedSubCategory ==  rs.getInt(1)){
													%>
									                              <option value="<%=rs.getString(1)%>" selected><%=rs.getString(2)%></option>
													<%
												
												}else{
													%>
									                              <option value="<%=rs.getString(1)%>"><%=rs.getString(2)%></option>
													<%
												}														
								  		}
								  		rs.close();
                                                                                pstmt.close();%>
								 					

							</select>
				<tr>
                            <td align="right" bgcolor="#FFFFFF" width="20%" class="formtext"><%= i18n.tr("Urgency") %></td>
                            <td width="80%" height="35" bgcolor="#FFFFFF" class="formfield">
                                    <select id="urgencyID" name="urgencyID" class="mcopy" style="width:180px" >  
                                            <option value="0" selected ><%= i18n.tr("---- choose ----") %></option>
                                                <%
                                                    pstmt = conn.prepareStatement("select sm.ID,sm.Name from sd_uip_master sm,sd_uip_details sd where sm.ID=sd.Id and sm.Status=0 and sm.Type=1 and sd.ParameterID=1 and sd.ParameterValue=? and sm.ProjectID=? order by sd.ID");
                                                    pstmt.setInt(1,selectedService);
                                                     pstmt.setInt(2,selectedProject);
                                                    rs=pstmt.executeQuery();
                                                    while(rs.next()){
                                                        if(UrgencyID ==  rs.getInt(1)){												  
                                                %>
                                                            <option value="<%=rs.getInt(1)%>" selected><%=rs.getString(2)%></option>
                                                <%
                                                     }else{
                                                %>
                                                            <option value="<%=rs.getInt(1)%>"><%=rs.getString(2)%></option>
                                                <%
                                                    }														
                                                  }
                                                rs.close();
                                                pstmt.close();%>		
                                    </select>
                            </td>
                       </tr>
                       <tr>
                            <td align="right" bgcolor="#FFFFFF" width="20%" class="formtext"><%= i18n.tr("Impact") %></td>
                            <td width="80%" height="35" bgcolor="#FFFFFF" class="formfield">
                                    <select id="impactID" name="impactID" class="mcopy" style="width:180px" >  
                                            <option value="0" selected ><%= i18n.tr("---- choose ----") %></option>
                                               <%
                                                pstmt = conn.prepareStatement("select sm.ID,sm.Name from sd_uip_master sm,sd_uip_details sd where sm.ID=sd.Id and sm.Status=0 and sm.Type=2 and sd.ParameterID=1 and sd.ParameterValue=? and sm.ProjectID=? order by sd.ID");   
                                                pstmt.setInt(1,selectedService);
                                                pstmt.setInt(2,selectedProject);
                                                rs=pstmt.executeQuery();
                                                   while(rs.next()){
                                                            if(ImpactID ==  rs.getInt(1)){												  
                                               %>
                                            <option value="<%=rs.getInt(1)%>" selected><%=rs.getString(2)%></option>
                                            <%
                                               }else{
                                            %>
                                            <option value="<%=rs.getInt(1)%>"><%=rs.getString(2)%></option>
                                            <%
                                                }														
                                              }
                                            rs.close();
                                            pstmt.close();%>		
                                    </select>
                            </td>
                       </tr>	
                       <tr>
							      <td  align="right" bgcolor="#FFFFFF" class="formtext"  width="20%"><%= i18n.tr("Mode") %></td>
							      <td  height="35" bgcolor="#FFFFFF" class="formfield" width="80%">  
							     <select name="submit_through" id="submit_through" class="mcopy" style="width:180px" >
						 	     <option value="0">E-mail</option>

							<%
                                                  pstmt = conn.prepareStatement(" Select sourceFilterID,FilterName from sd_sourcefilter where ProjectID = ?");
					          pstmt.setInt(1,selectedProject);
                                                  rs=pstmt.executeQuery();
			                  
			                  while(rs.next())
			                  {	
			                	  if(selectedMode==rs.getInt("sourceFilterID"))
			                  	{%>
			                			<option value="<%=rs.getInt(1)%>" selected ><%=rs.getString(2)%></option>
			                  <%	}
			                	  else{
								%>
										<option value="<%=rs.getInt(1)%>"><%=rs.getString(2)%></option>
									
								<%
								}
			                  } 
                                          rs.close(); 
                                          pstmt.close();
						 %>
                          
                           
								   </select>
							      </td>
				      </tr>
			  </td>
                       </tr> 
							
	   
					  	
						 	    
		 			<tr>
		 				<td height="14" colspan="2">&nbsp;</td>
		 			</tr>
                   </table>
                      <table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr align="center" class="basicButtonFooter">

                        
                        <td colspan="2" bgcolor="#FFFFFF" class="domains topMargin10" align="center">
                            <input id="testButton"  type="button"  name="testButton" onClick="test()" value="Test"  class="addbuttons greenBtn" />
                                <input type="hidden" name="check_value" value=""/>
                                <input type="hidden" name="MailDetails_ID" value="<c:out value="<%=MailDetails_ID%>"/>"/>
                             <input type="hidden" name="PageType" value="<%=PageType%>"/>
                         <%
                         	if(request.getParameter("edit") != null){
                         		%>
                                        <input  type="button" value="Update" id="updateButton"  class="addbuttons greenBtn" />
                         		<%
                         	}else{
                         		%>
                                        <input  type="button" value="Add" id="addButton" class="addbuttons greenBtn" />
                         		<%
                         	}
                          %>
              		     
                              <input  type="button"  ONCLICK="javascript:window.history.back()" value=<%= i18n.tr("Cancel") %>  class="addbuttons" />
                          </td>

                        
		                      </tr>
		                    </table>
                        </div></div></div>
                        </td>
		                </tr>
		              </table>
                          <div class="widgetFooter"></div>   
		               </td>    
		              </tr>
		             
                   </table>
 				 
             </td>
          </tr>
       </table>
       
     </td>
   </tr>
  </table>
 </form>
</div>
				<%
				}
			    catch(Exception e){
					
				        logger.error("In MailServerConfiguration.jsp ***** "+e.getMessage());
                                        StackTraceElement[] stackTrace=null;
                                        stackTrace=e.getStackTrace();
                                        for(int i=0;i<stackTrace.length;i++){
                                              logger.error(" ---- "+stackTrace[i].toString());
                                        }
				
			    }
			    finally{
				   try{
	
					if(pstmt!=null)
					  pstmt.close();
	
					if(conn!=null)
					  conn.close();

        		    }catch(Exception e)
                            {
                                logger.error("In finally catch of MailServerConfiguration.jsp ***** "+e.getMessage());
                                        StackTraceElement[] stackTrace=null;
                                        stackTrace=e.getStackTrace();
                                        for(int i=0;i<stackTrace.length;i++){
                                              logger.error(" ---- "+stackTrace[i].toString());
                                        }
                            }
        
                 } %>
 <%@ include file="Sapphire_Footer.jsp" %>
<script type='text/javascript'>
$( window ).on( "load", function(e) {
    var sql_import_export = $("#returnQueryBuilderData").val();
    e.preventDefault();
    if(sql_import_export != null && sql_import_export !== '' && sql_import_export != undefined){
        $('#builder').queryBuilder('setRulesFromSQL', sql_import_export);
    }
});
</script>
</body>
</html>
<script type="text/javascript">
    Ext.require([
    'Ext.form.field.ComboBox',
    'Ext.form.FieldSet',
    'Ext.tip.QuickTipManager',
    'Ext.data.*'
]);
    Ext.require([
    'Ext.ux.form.field.BoxSelect'
]);
Ext.Loader.setConfig({
    enabled: true
});
Ext.Loader.setPath('Ext.ux', 'ext/examples/ux/');
</script>
<script type="text/javascript">
   
  Ext.onReady(function() {
    Ext.tip.QuickTipManager.init();
    
    Ext.define('modelData', {
        extend: 'Ext.data.Model',        
       fields:[ {type:'string',name:'column1'},
                {type:'string',name:'column2'}
        ],        
        idProperty: 'threadid'
    });
    
    var Userstore = Ext.create('Ext.data.Store', {
        remoteSort:true,
        autoLoad :true,
        model: 'modelData',
        proxy:{
            type:'ajax',
            url:'GetJsonObject?module=1',
            reader : {
                totalProperty:'total',
                root:'rows'               
            }
        }         
            
    });
    
    var UserListBox = Ext.create('Ext.form.field.ComboBox', {

        store: Userstore,        
        typeAhead: true,
        width:280,
        selectOnFocus:true,
        cls : 'mcopy',
        minChars:0,
        emptyText:'-- Select User -- ',
        displayField:'column2',
        valueField:'column1',       
        renderTo: 'users1',        
        itemSelector: 'div.search-item',           
        forceSelection:true,
        listeners : {       
            select : function(cmb,r){
                    this.setValue(r,true);
                    document.getElementById("users").value = this.getValue();         
                    document.getElementById("username").value = this.getRawValue();
                    this.collapse(); 
                }
              }
       
    });
  
    
   UserListBox.on('change', function() {document.getElementById("users").value = this.getValue();document.getElementById("username").value = this.getRawValue(); });
    
  });
  function changeproject(){
      var project = document.getElementById("project").value;
      if(project === ""){
        $('#ServiceLine').empty();
        $('#ServiceLine').append("<option value='0' selected>---- choose ----</option>");
        $('#category').empty();
        $('#category').append("<option value='0' selected>---- choose ----</option>");
        $('#subCategoryId').empty();
        $('#subCategoryId').append("<option value='0' selected>---- choose ----</option>");
        $('#urgencyID').empty();
        $('#urgencyID').append("<option value='0' selected>---- choose ----</option>");
        $('#impactID').empty();
        $('#impactID').append("<option value='0' selected>---- choose ----</option>");
        $('#submit_through').empty();
        $('#submit_through').append("<option selected value='0'>E-mail</option>");
      }else{
        jQuery.ajax({
           url: "GetJsonObject",
           type: 'GET',
           contentType: "json",
           data: "module=86&projectId="+document.getElementById("project").value,
           async: false,
           success: function(data2) {
               $('#ServiceLine').empty();
               $('#ServiceLine').append("<option value='0' selected>---- choose ----</option>");
               var result = jQuery.parseJSON(data2);
               var option = [];
               $.each(result, function(key,obj) {
                   option.push($("<option></option>").attr("value", obj.ID).text(obj.value).prop("outerHTML"));
    });
               $('#ServiceLine').append(option.join(''));
           },complete:function(){
               $('#category').empty();
               $('#category').append("<option value='0' selected>---- choose ----</option>");
               $('#subCategoryId').empty();
               $('#subCategoryId').append("<option value='0' selected>---- choose ----</option>");
               $('#urgencyID').empty();
               $('#urgencyID').append("<option value='0' selected>---- choose ----</option>");
               $('#impactID').empty();
               $('#impactID').append("<option value='0' selected>---- choose ----</option>");
               loadMode();
           }
    });
            }
            }
    function changeService(){
        var serviceId = document.getElementById("ServiceLine").value;
        if(serviceId === ""){
            $('#category').empty();
            $('#category').append("<option value='0' selected>---- choose ----</option>");
            $('#subCategoryId').empty();
            $('#subCategoryId').append("<option value='0' selected>---- choose ----</option>");
            $('#urgencyID').empty();
            $('#urgencyID').append("<option value='0' selected>---- choose ----</option>");
            $('#impactID').empty();
            $('#impactID').append("<option value='0' selected>---- choose ----</option>");
        }else{
            jQuery.ajax({
               url: "GetJsonObject",
               type: 'GET',
               contentType: "json",
               data: "module=87&projectId="+document.getElementById("project").value+"&serviceId="+serviceId,
               async: false,
               success: function(data2) {
                   $('#category').empty();
                   $('#category').append("<option value='0' selected>---- choose ----</option>");
                   var result = jQuery.parseJSON(data2);
                   var option = [];
                   $.each(result, function(key,obj) {
                       option.push($("<option></option>").attr("value", obj.ID).text(obj.value).prop("outerHTML"));
                   });
                   $('#category').append(option.join(''));
               },complete:function(){
                    $('#subCategoryId').empty();
                    $('#subCategoryId').append("<option value='0' selected>---- choose ----</option>");
                    loadUrgency();
                    loadImpact();
        }
           });
        }
    }
   function loadUrgency(){
    var serviceId = document.getElementById("ServiceLine").value;
    jQuery.ajax({
        url: "GetJsonObject",
        type: 'GET',
        contentType: "json",
        data: "module=83&projectId="+document.getElementById("project").value+"&serviceId="+serviceId,
        async: false,
        success: function(data2) {
            $('#urgencyID').empty();
            $('#urgencyID').append("<option value='0' selected>---- choose ----</option>");
            var result = jQuery.parseJSON(data2);
            var option = [];
            $.each(result, function(key,obj) {
                option.push($("<option></option>").attr("value", obj.ID).text(obj.value).prop("outerHTML"));
    });
            $('#urgencyID').append(option.join(''));
        },complete:function(){
        }
    });
  }
     function loadImpact(){
    var serviceId = document.getElementById("ServiceLine").value;
    jQuery.ajax({
        url: "GetJsonObject",
        type: 'GET',
        contentType: "json",
        data: "module=84&projectId="+document.getElementById("project").value+"&serviceId="+serviceId,
        async: false,
        success: function(data2) {
            $('#impactID').empty();
            $('#impactID').append("<option value='0' selected>---- choose ----</option>");
            var result = jQuery.parseJSON(data2);
            var option = [];
            $.each(result, function(key,obj) {
                option.push($("<option></option>").attr("value", obj.ID).text(obj.value).prop("outerHTML"));
    });
            $('#impactID').append(option.join(''));
        },complete:function(){
        }
    });
            }
  function loadMode(){
    jQuery.ajax({
        url: "GetJsonObject",
        type: 'GET',
        contentType: "json",
        data: "module=85&projectId="+document.getElementById("project").value,
        async: false,
        success: function(data2) {
            $('#submit_through').empty();
            var result = jQuery.parseJSON(data2);
            var option = [];
            $.each(result, function(key,obj) {
                option.push($("<option></option>").attr("value", obj.ID).text(obj.value).prop("outerHTML"));
        });
            $('#submit_through').append(option.join(''));

        },complete:function(){
        }
    });
    }
    function changeCategory(){
        var categoryId = document.getElementById("category").value;
        if(categoryId === "" || categoryId === "---- choose ----"){
            $('#subCategoryId').empty();
            $('#subCategoryId').append("<option value='0' selected>---- choose ----</option>");
        }else{
            var serviceId = document.getElementById("ServiceLine").value;
            var categoryId = document.getElementById("category").value;
            jQuery.ajax({
               url: "GetJsonObject",
               type: 'GET',
               contentType: "json",
               data: "module=82&projectId="+document.getElementById("project").value+"&serviceId="+serviceId+"&categoryId="+categoryId,
               async: false,
               success: function(data2) {
                   $('#subCategoryId').empty();
                   $('#subCategoryId').append("<option value='0' selected>---- choose ----</option>");
                   var result = jQuery.parseJSON(data2);
                   var option = [];
                   $.each(result, function(key,obj) {
                       option.push($("<option></option>").attr("value", obj.ID).text(obj.value).prop("outerHTML"));
                   });
                   $('#subCategoryId').append(option.join(''));
               },complete:function(){
        }
           });
    }
        }
</script>
        
<script>
    $("#updateButton").click(validatePage);
    $("#addButton").click(validatePage);
    $('#builder').queryBuilder({
        filters: [{
	    id: 'cc',
	    label: 'Cc',
	    type: 'string',
            operators: ["equal", "not_equal", "contains", "not_contains", "begins_with", "not_begins_with"]
	  },{
	    id: 'description',
	    label: 'Description',
	    type: 'string',
            operators: ["equal", "not_equal", "contains", "not_contains", "begins_with", "not_begins_with"]
	  },{
	    id: 'from',
	    label: 'From',
	    type: 'string',
            operators: ["equal", "not_equal", "contains", "not_contains", "begins_with", "not_begins_with"]
	  },{
	    id: 'subject',
	    label: 'Subject',
	    type: 'string',
            operators: ["equal", "not_equal", "contains", "not_contains", "begins_with", "not_begins_with"]
	  },{
	    id: 'to',
	    label: 'To',
	    type: 'string',
            operators: ["equal", "not_equal", "contains", "not_contains", "begins_with", "not_begins_with"]
	  },]
    });
</script>
<% String transportType=request.getParameter("transport");
if(transportType!=null) {%>
<script>
    jQuery(function(){
            jQuery("#<%=transportType%>").click();
    });
</script>
<%}%>