<%
/********************************************************************************************************
*
*   Name			:	egLogin.jsp
*   Purpose			:	Login Page for eG Enterprise
*   Version			:	4.0
*   CreationDate	:	05/09/2006
*	Author          :   L. Vijayakumar
*******************************************************************************************************/
%>
<!DOCTYPE html>

<meta charset="utf-8" http-equiv="X-UA-Compatible" content="IE=8,9,10" >
<%@ page import="com.eg.EgBackgroundSetting" %>
<%@ page import = "com.eg.IniFile"%>
<%@ page import="com.eg.EgInstallInfo" %>
<%@ page import = "com.egurkha.util.StringUtils" %>
<%@ page import = "com.egurkha.ini.IniUI" %>
<%@ page import = "com.egurkha.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.Vector" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.Calendar" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.StringTokenizer" %>
<%@ taglib prefix="egui" uri="WEB-INF/eg-taglib.tld"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%
try
{
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	String msg="admin.login.Signing you in";
	com.egurkha.ini.IniUI trackerUI = (com.egurkha.ini.IniUI)com.egurkha.ini.IniUI.getInstance();
	String trackerLanguage = trackerUI.getDefaultLanguage();
	String sessionID =session.getId();
	
	IniFile dbIniObj = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_services.ini");
	String dbConfigured = dbIniObj.getValue("START MANAGER","DBconfigured");
	String mgrFirstStepConfiguration=dbIniObj.getValue("START MANAGER","mgrFirstStepConfiguration");
	File licenseObj = new File(EgInstallInfo.getInstallDir()+"/bin/license");

	if (licenseObj == null || 
		(licenseObj != null && !licenseObj.exists()) || 
		dbConfigured == null || 
		(dbConfigured != null && (dbConfigured.trim().length() == 0 || dbConfigured.equalsIgnoreCase("false"))) ||
		mgrFirstStepConfiguration == null ||
		(mgrFirstStepConfiguration != null && (mgrFirstStepConfiguration.trim().length() == 0 || mgrFirstStepConfiguration.equalsIgnoreCase("false"))))
	{
		application.getRequestDispatcher("/eGDatabaseCreation.jsp").forward(request,response);
	}

	IniFile controlModeUIni =  new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini");
	String RightClikMode = controlModeUIni.getValue("MODE_OF_OPERATION","rightClick");
	String SelectionMode = controlModeUIni.getValue("MODE_OF_OPERATION","selection");
	String loginSkin = controlModeUIni.getValue("DEFAULT_THEME","LoginScreen");
	String uName=request.getParameter("userName");
	if (uName == null && StringUtils.isNull(uName))
	{
		uName = (String)request.getAttribute("userName");
	}
	String idpResponse = request.getParameter("idpResponse");

	if (idpResponse == null || idpResponse.equals(""))
	{
		idpResponse = "";
	}

	UserRegistry registry =UserRegistry.getInstance();
	/*User _user = registry.getUser(sessionID,true);
	if(_user!=null)
	{
		String trackerUserLang = _user.getLanguage();
		if (trackerUserLang!=null && !trackerUserLang.equalsIgnoreCase("NULL"))
		{
			trackerLanguage=trackerUserLang;
		}
	}*/

	String script_src="script_item_"+trackerLanguage+".js";

	//-------Print Current year --------------
		int currYear = 0;

		Calendar cal = Calendar.getInstance();
		currYear = cal.get(cal.YEAR);
	//-------Print Current year---------------

	if(EgInstallInfo.isSuperManager)
	{
		com.eg.EgManagersInfo mgrInfo = com.eg.EgManagersInfo.getInstance();
		java.util.Hashtable reportingManagers = mgrInfo.getReportingManagers();
		if(reportingManagers != null && !reportingManagers.isEmpty())
		{
			ArrayList repMgrIds = new ArrayList(reportingManagers.keySet());
			if(repMgrIds != null && !repMgrIds.isEmpty())
			{
				com.eg.supermanager.SmSessionData smsData = new com.eg.supermanager.SmSessionData(session.getId(),repMgrIds);
				com.eg.supermanager.EgThreadLocal egtl = new com.eg.supermanager.EgThreadLocal();
				egtl.set(smsData);
			}
		}
	}

	IniFile iniFile = new IniFile(EgInstallInfo.getInstallDir() +"/manager/config/eg_authenticate.ini");
	ArrayList egLoggingSystem = new ArrayList();
	//egLoggingSystem.add("eG Enterprise");
	String[] domains = iniFile.getSubjects();
	if (domains != null && domains.length > 0)
	{
		for(int i=0;i<domains.length; i++)
		{
			if(!egLoggingSystem.contains(domains[i]))
			{
				egLoggingSystem.add(domains[i]);
			}
		}
	}

	boolean hasMultiLoginTypes = false;
	boolean hasSsoLoginEnabled = false;
	IniFile ssoIniObj = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_samlsso.ini");
	String enableSSOLogin = ssoIniObj.getValue("SAML_SSO","SSO_ENABLED");
	if(enableSSOLogin!=null && (enableSSOLogin.equalsIgnoreCase("yes") || enableSSOLogin.equalsIgnoreCase("true")))
	{
		hasSsoLoginEnabled = true;
	}

	String strDefaultLoginIdp = ssoIniObj.getValue("SAML_SSO","defaultIdPForLogin");
	if(com.egurkha.util.StringUtils.isNull(strDefaultLoginIdp))
	{
		strDefaultLoginIdp = "";
	}

	ArrayList egLoggingIdp = new ArrayList();
	String[] idpList = ssoIniObj.getSubjects();
	if (idpList != null && idpList.length > 0) 
	{
		for (int i = 0; i < idpList.length; i++) 
		{
			if (!com.egurkha.util.StringUtils.isNull(idpList[i]) && (idpList[i].equals("SAML_SSO") || idpList[i].startsWith("SECONDARY_")))
			{
				continue;
			}
			if (!egLoggingIdp.contains(idpList[i])) 
			{
				egLoggingIdp.add(idpList[i]);
			}
		}
	}

	boolean isDomainConfigured = (domains != null && domains.length > 0);

	hasMultiLoginTypes = (isDomainConfigured || (hasSsoLoginEnabled && (egLoggingIdp != null && egLoggingIdp.size() > 0)))? true : false;
	String user_logging = (String)controlModeUIni.getValue("USER_SIGN_IN","defaultAdminSignedIn");
	String enableFirstTimeLogging = (String)controlModeUIni.getValue("USER_SIGN_IN","enableFirstTimeSigningIn");
	if (user_logging == null || user_logging.equals(""))
	{
		user_logging = "true";
	}
	if (enableFirstTimeLogging == null || enableFirstTimeLogging.equals(""))
	{
		enableFirstTimeLogging = "false";
	}
	boolean isUserLoggingFirstTime = (user_logging.equalsIgnoreCase("false"));
	boolean enableFTL= (enableFirstTimeLogging.equalsIgnoreCase("true"));
	IniUI ui = IniUI.getInstance();	
	String themeIco="eg.ico";
	if(ui.isHKTThemeEnabled())
	{
		themeIco = ui.getHKTThemeICO();
		if(StringUtils.isNull(themeIco))
		{
			themeIco="eg.ico";
		}
	}

	IniFile mgrIniObj = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_mgrmisc.ini");
	String hideForgetPassword = mgrIniObj.getValue("MISC_ARGS","hideForgetPassword");
	boolean hideForgetPass = false;
	if (hideForgetPassword != null && (hideForgetPassword.equalsIgnoreCase("true") || hideForgetPassword.equalsIgnoreCase("yes")))
	{
		hideForgetPass = true;
	}
%>

<jsp:useBean id="configmsg" scope="page" class="egurkha.TransactionBean" />
<html>
<head>
<meta name="robots" content="noindex, nofollow">
<link rel="shortcut icon" href="/final/<%=themeIco%>">
<style>
.dbfont_normal12_alink{
font-size:12px;
font-family: 'LucidaGrandeRegular';
text-decoration:underline;
color:#64a5fa;
}
.x-mask{background:#000!important;filter:alpha(opacity=90)!important;opacity:.9!important} 

</style>
<%
	String loggedInDomain = "";
	String loggedInIdp = "";
	Vector errVector = (Vector) request.getAttribute("vec_Errors_new");
	String errText ="none";
	if(errVector!=null)
		errText = (String)errVector.get(0);
	String loggedOutUser = (String)request.getAttribute("loggedOutUser");
	configmsg.createFile("eg_services.ini");
	String title = configmsg.getStrValue("MISC_ARGS","ManagerTitle");
	if (title == null || title.equals(""))
	{
		title = "eG Innovations, Inc.";
	}
	if(ui.isHKTThemeEnabled())
	{
		String hktThemeTitle = ui.getHKTThemeTitle();
		
		if(!StringUtils.isNull(hktThemeTitle))
		{
			title=hktThemeTitle;
		}
		if(StringUtils.isNull(title))
		{
			title="xMonPlus";
		}
	}
	String defaultDomain = configmsg.getStrValue("MISC_ARGS","defaultDomainForLogin");
	boolean hasDefaultDomain = false;
	if (defaultDomain == null || defaultDomain.length() < 1)
	{
		defaultDomain = "";
	}

	if (!com.egurkha.util.StringUtils.isNull(defaultDomain) &&  (egLoggingSystem != null && egLoggingSystem.contains(defaultDomain)))
	{
		hasDefaultDomain = true;
	}

	

	if (loggedOutUser == null || loggedOutUser.length() == 0)
	{
		loggedOutUser = "";
	}
	
	if (!loggedOutUser.startsWith("samlsso/") && loggedOutUser.indexOf("/") != -1)
	{
		loggedInDomain = loggedOutUser.substring(0,loggedOutUser.indexOf("/"));
		loggedOutUser = loggedOutUser.substring(loggedOutUser.indexOf("/")+1);
	}
	else if(loggedOutUser.startsWith("samlsso/"))
	{
		StringTokenizer token1 = new StringTokenizer(loggedOutUser, "/");
		String idpType = (String) token1.nextElement();
		String IdpName = (String) token1.nextElement();
		loggedInIdp = IdpName;
		loggedOutUser = "";
	}
	String nonDomainUser = loggedOutUser;
	String fromCA = request.getParameter("fromCA");
	if (StringUtils.isNull(fromCA) || fromCA.trim().equalsIgnoreCase("null"))
	{
		fromCA = "";
	}

	String strDefaultAuthType = configmsg.getStrValue("MISC_ARGS","AuthenticationModeForLogin");
	if (StringUtils.isNull(strDefaultAuthType))
	{
		strDefaultAuthType = "eG Enterprise";
	}

	if (hasMultiLoginTypes)
	{
		boolean isIDPConfigured = (hasSsoLoginEnabled && (egLoggingIdp != null && egLoggingIdp.size() > 0));

		if (strDefaultAuthType.equalsIgnoreCase("SAML"))
		{
			if (!isIDPConfigured)
			{
				strDefaultAuthType = "eG Enterprise";
			}
		}
		else if (strDefaultAuthType.equalsIgnoreCase("Domain"))
		{
			if (!isDomainConfigured)
			{
				strDefaultAuthType = "eG Enterprise";
			}
		}
	}

	//Value obtained from EgAdminNavBar(newWindow function)
	String monitorlogin = request.getParameter("monitorlogin");
	if(monitorlogin != null && monitorlogin.equalsIgnoreCase("yes"))
	{
%>
		<title> <%=title%>Monitor Home</title>
<%
	}
	else
	{
%>
		<title> <%=title%></title>
<%
	}
	
	

	String imageName = ui.getHomepageLogo();
	if(EgInstallInfo.isSuperManager)
	{
		ArrayList extensionList = new ArrayList();
		extensionList.add("gif");
		extensionList.add("jpeg");
		extensionList.add("jpg");
		extensionList.add("png");
		for (int ext = 0; ext < extensionList.size(); ext++)
		{
			String strExtension = (String)extensionList.get(ext);
			File sourceFile = new File(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/admin/eg_images/egsm_login."+strExtension);
			if (sourceFile.exists())
			{
				imageName="/final/admin/eg_images/egsm_login."+strExtension;
				break;
			}
		}
	}
	else if(uName!=null && !uName.equals(""))
	{
		loggedOutUser = uName;
		//saml user
		if(loggedOutUser.startsWith("samlsso/"))
		{
			String idpName=uName.substring(uName.indexOf("/")+1,uName.lastIndexOf("/"));
			String userName=uName.substring(uName.lastIndexOf("/")+1,uName.length());
			uName="samlsso/"+idpName+"/"+userName;
			loggedInIdp = idpName;
		}

		//for domain user
		if(!loggedOutUser.startsWith("samlsso/") && uName.indexOf("/")>-1)
		{
			String domainName=uName.substring(0,uName.indexOf("/"));
			loggedInDomain = domainName;
			String userName=uName.substring(uName.indexOf("/")+1,uName.length());
			if(userName.indexOf("Grp")>-1)
			{
				userName=userName.substring(userName.indexOf("/")+1,userName.length());
			}
			uName=domainName.toLowerCase()+"_"+userName;
		}

		ArrayList extensionList = new ArrayList();
		extensionList.add("gif");
		extensionList.add("jpeg");
		extensionList.add("jpg");
		extensionList.add("png");

		for (int ext = 0; ext < extensionList.size(); ext++)
		{
			String strExtension = (String)extensionList.get(ext);
			File sourceFile = new File(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/admin/eg_images/"+uName+"_login."+strExtension);
			if (sourceFile.exists())
			{
				imageName="/final/admin/eg_images/"+uName+"_login."+strExtension;
				break;
			}
		}
	}

	//if (!(loggedInDomain.length() > 0) && (!(loggedInIdp.length() > 0)))
	if (com.egurkha.util.StringUtils.isNull(loggedInDomain) &&	com.egurkha.util.StringUtils.isNull(loggedInIdp))
	{
		String isLocal = request.getParameter("isLocal");
		if (isLocal == null && StringUtils.isNull(isLocal))
		{
			isLocal = (String)request.getAttribute("isLocal");
		}
		if (isLocal != null && isLocal.equalsIgnoreCase("true"))
		{
			loggedInDomain = "eG Enterprise";
			strDefaultAuthType = "eG Enterprise";
		}
	}

	if (!com.egurkha.util.StringUtils.isNull(loggedInIdp))
	{
		strDefaultAuthType = "SAML";
	}
	else if (!com.egurkha.util.StringUtils.isNull(loggedInDomain) && !loggedInDomain.equals("eG Enterprise"))
	{
		strDefaultAuthType = "Domain";
	}

	String forgetpwd=request.getParameter("forget");

	String message = configmsg.getStrValue("MISC_ARGS","LogoText");

	
	boolean loginAuthentication = ui.isLoginAuthenticationEnabled();
	String scriptUserName = uName;
	if (uName != null && uName.indexOf("\\") != -1)
	{
		scriptUserName = findAndReplaceString(scriptUserName,"\\","\\\\");
	}
	
	if (loggedOutUser != null && loggedOutUser.indexOf("\\") != -1)
	{
		loggedOutUser = findAndReplaceString(loggedOutUser,"\\","\\\\");
	}
	
	if (nonDomainUser != null && nonDomainUser.indexOf("\\") != -1)
	{
		nonDomainUser = findAndReplaceString(nonDomainUser,"\\","\\\\");
	}
	String strLoginFooterText="&copy;&nbsp;eG Innovations, Inc. All Rights Reserved";

	if(ui.isHKTThemeEnabled())
	{
		strLoginFooterText = "&copy;&nbsp;"+ui.getHKTPDFFooterText()+"&nbsp;. All Rights Reserved";
	}

	String existingUser = "";
	String sessionId = session.getId();
	if (sessionId != null)
	{
		String fwdTo = (String)session.getAttribute("fwdTo");
		if (StringUtils.isNull(fwdTo))
		{
			User _user = registry.getUser(sessionID,true);
			if (_user != null)
			{
				existingUser = _user.getLoginID();
			}
		}
		else
		{
%>
		<script>
			window.location.href = "/final/servlet/com.egurkha.Logout";
		</script>
<%
		}
	}

	String eGMgrModel = configmsg.getStrValue("MISC_ARGS","eGMgrModel");
%>
<egui:skin ui=""/>
<script src="/final/admin/eg_scripts/validate.js"></script>
<script src="/final/monitor/eg_scripts/ajaxutils.js"></script>
<script src="/final/scripts/utilities/EncodeDecodeParams.js"></script>
<script src="/final/scripts/<%=script_src%>"></script>

<!-- ext js and css -->
<!-- script type="text/javascript" src="extjs/ext-all.js" ></script -->
<!-- fancy Scroll-->

<script>
var loginAlertTitle='<egui:intnl text="admin.login.eG LOGIN"/>';
var emptyPasswordAlert='<egui:intnl text="admin.login.Please enter the password"/>';
var emptyUserNameAlert='<egui:intnl text="admin.login.Please enter the username"/>';
</script>



<script language="JavaScript1.2">
// for 2fa - starts here
var resendCount = 0;
var maxResendCount = 0;
// 2fa - ends here
var hideForgetPass=<%=hideForgetPass%>;
var eGMgrModel='<%=eGMgrModel%>';
var strLoginFooterText='<%=strLoginFooterText%>';
var usrName='<%=scriptUserName%>';
var existingUser='<%=existingUser%>';
var defaultDomain = '<%=defaultDomain%>';
var hasDefaultDomain = eval('<%=hasDefaultDomain%>');
var isDomainConfigured=eval('<%=(!isDomainConfigured)%>');
var domainsConfigured=eval('<%=(isDomainConfigured)%>');
var hasMultiLoginTypes=eval('<%=(!hasMultiLoginTypes)%>');
var hasAuthenTypeCombo=eval('<%=hasMultiLoginTypes%>');
var hasSsoLoginEnabled = '<%=hasSsoLoginEnabled%>';
var loggedInDomain = '<%=loggedInDomain%>';
var loggedInIdp = '<%=loggedInIdp%>';
var idpResponse = '<%=idpResponse%>';
var loggedOutUser = '<%=loggedOutUser%>';
var nonDomainUser = '<%=nonDomainUser%>';
var isUserLoggingFirstTime = '<%=isUserLoggingFirstTime%>';
var enableFTL = '<%=enableFTL%>';
var errText = '<%=errText%>';
var currYear = '<%=currYear%>';
var imgname = '<%=imageName%>';
var logoImageName = '<%=imageName%>';
var logoMessage = '<%=message%>';
var isFromSuperManager = eval('<%=EgInstallInfo.isSuperManager%>');
var loginSkin = '<%=loginSkin%>';
/** To Disable Right Click */
var loginLogoImage='';
var message=""; 
var publicJson=""; 
var strDefaultAuthType="<%=strDefaultAuthType%>"; 
var strDefaultLoginIdp="<%=strDefaultLoginIdp%>"; 
if(logoImageName!=null && logoImageName.indexOf(".")>0)
{
	loginLogoImage='<div id="LoginLogoId" style="background-image:url(\''+logoImageName+'\');background-repeat:no-repeat;width:231px;height:71px;position:absolute;left:0px;top:20px;margin-left:30px"></div>';
}
else
{
	loginLogoImage='</div><div id="LoginLogoId" class="loginLogo"></div>';
}
var xmlhttp;

/** To Disable Right Click */
	var message="";
	function clickIE(){if(document.all){(message);return false;}}
	function clickNS(e){if(document.layers||(document.getElementById&&!document.all)){
	if(e.which==2||e.which==3){(message);return false;}}}
	if('<%=RightClikMode%>'=='production')
	{
		if (document.layers){document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
		else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}
		document.oncontextmenu=new Function("return false")
	}


	/**  To disable drag and selection */
	var alltables = document.getElementsByTagName("body");
	if ('<%=SelectionMode%>' == 'production') {
		window.onload = function() {
			function disableSelection(element) {
				element.onselectstart = function() {
					return false;
				};
				element.unselectable = "on";
				element.style.MozUserSelect = "none";
				element.style.cursor = "default";
			}

			for (var i = 0; i < alltables.length; i++) {

				disableSelection(alltables[i]); //disable text selection within all tables on the page
			}

		}
	}

function enter()
{
	//alert("---Man at work in egLogin.jsp, Sorry for inconvinent---");
	//document.indexForm.username.value="";
	//document.indexForm.password.value="";
	//document.indexForm.username.focus();
}

//forgot password changes starts here --lavanya

var intext;

/*
	this will be called to get password
	@see getpassword()
*/

function validating(indexForm)
{
	var userTogetpass = indexForm.findField("fusername").getValue();
	if(userTogetpass.length==0)
	{
		Ext.Msg.show({
					title:'eG LOGIN',
					 msg: '<egui:intnl text="admin.login.Please enter the username"/>'+'.',
					buttons: Ext.Msg.OK,
					icon:'iconExclamation'
				 });
		return false;
	}
	//if(userTogetpass.indexOf("\\")>-1 || userTogetpass.indexOf("/")>-1)
	if(userTogetpass.indexOf("/")>-1)
	{
		Ext.Msg.show({
					title:'eG LOGIN',
					 msg: '<egui:intnl text="admin.login.This feature is not available for domain users"/>'+'.',
					buttons: Ext.Msg.OK,
					icon: 'iconInformation'
				 });
		return false;
	}
	return true;
}

/*
	to hit mail servlet and send the mail
	@see validate()
*/

function getpassword()
{
	
	var divnew=document.getElementById("pwdDIV");
	//if(divnew!=null )
	//{
	//	intext=divnew.innerHTML;
	//}
	//loading();
	xmlhttp=null;
	if (window.XMLHttpRequest)
	{
		xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp!=null)
	{
		var params = "user="+encodeURIComponent(user);
		var url = "/final/servlet/com.eg.LoginHelperServlet";
		xmlhttp.onreadystatechange=state_Change2;
		xmlhttp.open('POST',url,true);
		xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		xmlhttp.setRequestHeader('Content-length',params.length);
		xmlhttp.setRequestHeader('Connection','close');
		xmlhttp.send(params);
	}
	else
	{
		alert('<egui:intnl text="admin.login.Your browser does not support XMLHTTP"/>');
	}
}

/*
	status gif
	@see getpassword()
*/
function loading()
{
	var log1=document.getElementById("loginError");
	//var myhtml = "<table border='0' height='100%'><tr><td valign='middle'><img src='/final/admin/eg_images/loading.gif'></td><td>LOADING</td></tr></table>";
	var myhtml = "<table border='0'><tr><td align='center' valign='middle'><img src='/final/admin/eg_images/load.gif'></td><td align='center'>Loading...</td></tr></table>";
	log1.innerHTML=myhtml;
}
/*
	state change to show the status (inner div logininfo2)
	@see getpassword()
*/
function state_Change2()
{
	var log3=document.getElementById("loginError");

	if (xmlhttp.readyState==4)
	{
		try
		{
			if (xmlhttp.status==200)
			{
				var val = xmlhttp.responseText;
				document.getElementById("loginError").innerHTML= val;
				$j("#getPassword").css("opacity",1.0);
				$j("#getPassword").addClass("mouse");
			}
			else
			{
				if(log3 != null)
				{
					log3.style.visibility="visible";
					log3.style.display="block";
					document.indexForm.userToGetPassword.focus();
					var msg = '<egui:intnl text="admin.login.Sorry! Problem occured while connecting to manager"/>'
					var myhtml = "<center><img align ='center'src='/final/admin/eg_images/fault.gif' width='25' height='25'><br>"+msg+"<br></center>";
					log3.innerHTML=myhtml;
					$j("#getPassword").css("opacity",1.0);
					$j("#getPassword").addClass("mouse");
				}
			}
		}catch (error)
		{
			//error
		}
	}
}

function showlogin()
{
	var divlogin=document.getElementById("pwdDIV");
	if(divlogin!=null)
	{
		divlogin.style.visibility="VISIBLE";
		divlogin.style.display="block";
		document.getElementById("pwdDIV").innerHTML=intext;
	}
	var divpwd=document.getElementById("loginDIV");
	if(divpwd!=null )
	{
		divpwd.style.visibility="hidden";
		divpwd.style.display="none";
	}
}

//forgot password changes ends here --lavanya

//login page

function valform(thisForm)
{
	
	var username=thisForm.findField("username").getValue();
	var password=thisForm.findField("password").getValue();
	if(!checkblank(username))
	{
		Ext.Msg.show({
						title:'eG LOGIN',
						 msg:'<egui:intnl text="admin.login.Please enter the username"/>'+'.',
						buttons: Ext.Msg.OK,
						icon: 'iconExclamation'
			});
		return false;
		//thisForm.username.focus();
	}
	else if (username.indexOf("..") > -1)
	{
			Ext.Msg.show({
						title:'eG LOGIN',
						 msg:_checkdots,
						buttons: Ext.Msg.OK,
						icon: 'iconExclamation'
			});
		return false;
	}
/*	else if(!checkspace(thisForm.uname))
	{
		thisForm.uname.focus();
	}
*/	else if(!checkblank(password) && (username.indexOf("/") == -1 && username.indexOf("\\") == -1))
	{
		Ext.Msg.show({
						title:'eG LOGIN',
						 msg:'<egui:intnl text="admin.login.Please enter the password"/>'+'.',
						buttons: Ext.Msg.OK,
						icon: 'iconExclamation'
			});
		return false;
	}
	return true;
}








//	status gif

function loading1()
{
	var log2 = document.getElementById("loginError");
	if(log2 != null && log2 != "Undefined")
	{
		log2.style.visibility="visible";
		log2.style.display="block";
		var msg="<egui:intnl text='<%=msg%>'/>...";
		var myhtml = "<table cellspacing='0' cellpadding='0' border='0' width='100%'><tr><td align='center'><table border='0'><tr><td align='center'><img src='/final/admin/eg_images/load.gif'></td> <td>"+msg+"</td></tr></table></td></tr></table>";
		log2.innerHTML=myhtml;
	}
}
/*
	to hit mail servlet and Encrypt the username and password
*/

function encrypting(thisForm)
{
	
	var username=thisForm.findField("username").getValue();
	var password=thisForm.findField("password").getValue();

	//username=username.replace("\\",'/');
	if (thisForm.findField("domainCombo") != null && thisForm.findField("domainCombo") != "undefined")
	{
		var userLogging=thisForm.findField("domainCombo").getValue();
		if (userLogging != null && userLogging != "eG Enterprise")
		{
			username = userLogging +"/"+username;
		}
	}
	
	if(username!=null && username!="")
	{
		
		return username+"~!~"+password;
	}
	
}

/*
	state change to show the status (div loginStatusDIV)
	& status gif
*/

function cryptStateChange()
{
	if (xmlhttp.readyState==4)
	{
		if (xmlhttp.status==200)
		{
			var v = xmlhttp.responseText;
			var log2=document.getElementById("loginStatusDIV");
			if(log2!=null&&log2!="Undefined")
			{
				log2.style.visibility="visible";
				log2.style.display="block";
				var valStr= '<egui:intnl text="admin.login.Validating your login"/>';
				var myhtml = "<table cellspacing='0' cellpadding='0' border=0 width='100%'><tr><td align='center'><table border='0'><tr><td align='right'><img src='/final/admin/eg_images/load3.gif'></td><td>"+valStr+"...</td></tr></table></td></tr></table>";
				log2.innerHTML=myhtml;
			}
			verifying(v);
		}
		else
		{
			var log2=document.getElementById("loginStatusDIV");
			if(log2!=null&&log2!="Undefined")
			{
				log2.style.visibility="visible";
				log2.style.display="block";
				var sorryStr = '<egui:intnl text="admin.login.Sorry! Problem occured while logging in"/>';
				var myhtml = "<center><img align ='center'src='/final/admin/eg_images/fault.gif' width='25' height='25'><br>"+sorryStr+".</center>"; //<br>ReadyStateCode:"+xmlhttp.readyState+"/Status Code:"+xmlhttp.status+"<br>"+xmlhttp.responseText+"</center>";
				log2.innerHTML=myhtml;
			}
			/*else
			{
				alert("wwwProblem retrieving data:" + xmlhttp.statusText);
			}*/
			var thisForm = document.indexForm;
			//thisForm.validate.disabled=false;
		}
	}
}
/*
	to hit Login servlet and display error or redirects to index page
*/

function verifying(v)
{
	if(v!=null&&v!="")
	{
		var myarr = v.split("~!~");
		xmlhttp=null;

		if (window.XMLHttpRequest)
		{
			xmlhttp=new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		if (xmlhttp!=null)
		{
			var params = "uname="+myarr[0]+"&upass="+encodeURIComponent(myarr[1]);
			var url = "/final/servlet/com.egurkha.LoginServlet";
			xmlhttp.onreadystatechange=validateStateChange;
			xmlhttp.open('POST',url,true);
			xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			xmlhttp.setRequestHeader('Content-length',params.length);
			xmlhttp.setRequestHeader('Connection','close');
			xmlhttp.send(params);
		}
		else
		{
			alert('<egui:intnl text="admin.login.Your browser does not support XMLHTTP"/>');
		}
	}
}
/*
	state change to show the status (div loginStatusDIV)
*/

function validateStateChange()
{
	var mydiv = document.getElementById("loginError");
	var thisForm = document.indexForm;
	if (xmlhttp.readyState==4)
	{
		if (xmlhttp.status==200)
		{
			var v = xmlhttp.responseText;
			
			var myarr = v.split(":");
			
			if(myarr[0]=="Error")
			{
				if (mydiv!=null&&mydiv!="Undefined")
				{
					thisForm.password.value="";
					thisForm.username.focus();
					mydiv.style.visibility="visible";
					mydiv.style.display="block";
					var errorText = myarr[1];
					if (errorText != null && ((errorText.indexOf("The password is incorrect") != -1) || (errorText.indexOf("password may be incorrect") != -1)))
					{
						thisForm.password.focus();
					}

					$j("#SubmitButton").css("opacity",1.0);
					$j("#SubmitButton").addClass("mouse");
					mydiv.innerHTML=errorText;
				}
			}
			else if (v == "/final/admin/egGroupUserEntry.jsp")
			{
				var log2=document.getElementById("loginStatusDIV");
				if(log2!=null&&log2!="Undefined")
				{
					log2.style.display = "none";
				}
				OpenConnectUsesDiv();
			}
			else
			{
				window.location.href ="/final"+v;
			}
		}
		else
		{
			var sorryStr = '';
			var errormsg='<center><br><egui:intnl text="admin.login.Sorry! Problem occured while logging in"/>.</center>';
			$j("#SubmitButton").css("opacity",1.0);
			$j("#SubmitButton").addClass("mouse");
			mydiv.innerHTML=errormsg;
		}
	}
}
//forgot password changes ends here --lavanya
var message="Copyright \251 2008 eG Innovations, Inc.";
function click(e)
{
	return;
	if (document.all)
	{
		if (event.button == 2)
		{
			alert(message);
			return false;
		}
	}
}

document.onmousedown=click;

/* Drag- Scripts  (Begin) */
function agent(v){ 
	return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); 
}

function xy(e,v){ 
	return(v?(agent('msie')?event.clientY+document.body.scrollTop:e.pageY):(agent('msie')?event.clientX+document.body.scrollTop:e.pageX)); 
}

function dragOBJ(d,e){
	var divId = d.id;
	function drag(e){ 
		if(!stop){ 
			tX = xy(e,1)+oY-eY; 
			tY = xy(e)+oX-eX; 
			setOpacity(d, 4);
			d.style.top= ((tX <= windowHeight)? tX : windowHeight)+'px';
			d.style.left=((tY <=windowWidth) ? tY : windowWidth)+'px';
		}
	}

	var oX=parseInt(d.style.left),oY=parseInt(d.style.top),eX=xy(e),eY=xy(e,1),tX,tY,stop;
	var windowWidth = document.body.clientWidth;
	var	windowHeight = document.body.clientHeight;

	document.onmousemove=drag; 
	document.onmouseup=function(){ 
		stop=1; 
		document.onmousemove=''; 
		document.onmouseup=''; 
		setOpacity(d, 10);
		bringToFront(d);
	};
}

function setOpacity(testObj, value) 
{
	testObj.style.opacity = value/10;
	testObj.style.filter = 'alpha(opacity=' + value*10 + ')';
}

/* Drag- Scripts  (End) */

function getAbsoluteDivs(){
	var arr = new Array();
	var all_divs = document.body.getElementsByTagName("DIV");
	var j = 0;
	for (i = 0; i < all_divs.length; i++)
		if (all_divs.item(i).style.position=='absolute'){
			arr[j] = all_divs.item(i);
			j++;
		}
	return arr;
}

function bringToFront(obj){
	if (!document.getElementsByTagName)
		return;

	var divs = getAbsoluteDivs();
	var max_index = 0;  
	var cur_index;

	for (i = 0; i < divs.length; i++){
		var item = divs[i];
		if (item == obj || item.style.zIndex == '')
			continue;
		cur_index = parseInt(item.style.zIndex);
		if (max_index < cur_index){
			max_index = cur_index;
		}
	}
	obj.style.zIndex = max_index + 1;
}

function hide_centered_box(id)
{
	var closediv = document.getElementById(id);
	$j("#SubmitButton").css("opacity",1.0);
	$j("#SubmitButton").addClass("mouse");
	if (closediv != null)
	{
		closediv.style.display='none';
		//document.parent.validate.disabled=false;
		//alert(window.opener.document.indexForm.validate);//.validate.disabled = false;
		//document.indexForm.validate.disabled = false;
		var log2=document.getElementById("loginStatusDIV");
		if(log2!=null&&log2!="Undefined")
		{
			log2.style.display = "none";
		}
	}
}

function OpenConnectUsesDiv()
{
	var href = "/final/admin/egGroupUserEntry.jsp";

	var connectDiv = document.getElementById("connectDiv");
	var connectFrame = document.getElementById("connectFrame");
	if(connectDiv!=null){
		connectFrame.src = href;
		connectDiv.style.textAlign = 'right';
		connectDiv.style.padding = '0px';
		connectDiv.style.padding = '0px';
		connectDiv.style.background='transparent';
		connectDiv.style.display = 'block';
		connectDiv.style.position = 'absolute';
		bringToFront(connectDiv);
	}
}

function setLogonDomain()
{
	var domainID = document.getElementById("userLogging");
	var username=document.indexForm.username.value;
	if (domainID != null && username != null && domainID != "undefined")
	{
		username = username.toLowerCase();
		if (username == "admin" || username == "supermonitor")
		{
			domainID.selectedIndex = 0;
			//domainID.options[0].selected = true;
		}
	}
}
</script>

<script src="/final/jquery/jquery.js"></script>
<script src="/final/styles/jscrollpane/jquery.jscrollpane.js" ></script>
<script src="/final/styles/jscrollpane/jquery.mousewheel.js" ></script>
<script src="/final/styles/jscrollpane/mwheelIntent.js" ></script>
<script>

	$(function() {
		document.body.onkeydown = function (e) {
			if (e.which == 116 || (e.keyCode == 82 && e.ctrlKey))
			{
				var stateObj_admin = { foo: 1000 + Math.random()*1001 };
				history.pushState(stateObj_admin, "....", "/final/login");
			}
		}
	});

	// Disabling the browser back button - starts here
	(function (global) { 

		if(typeof (global) === "undefined") {
			throw new Error("window is undefined");
		}

		var _hash = "!";
		var noBackPlease = function () {
			global.location.href += "#";

			global.setTimeout(function () {
				global.location.href += "!";
			}, 50);
		};

		global.onhashchange = function () {
			if (global.location.hash !== _hash) {
				global.location.hash = _hash;
			}
		};

		global.onload = function () {
			noBackPlease();

			// disables backspace on page except on input fields and textarea..
			document.body.onkeydown = function (e) {
				var elm = e.target.nodeName.toLowerCase();
				if (e.which === 8 && (elm !== 'input' && elm  !== 'textarea')) {
					e.preventDefault();
				}
				// stopping event bubbling up the DOM tree..
				e.stopPropagation();
			};
			if (existingUser != null && existingUser.length > 0)
			{
				//verifying(existingUser+"~!~");
				window.location.href = "/final/egm";
			}
			else if ('<%=loginAuthentication%>' == 'false')
			{
				if (usrName == null || usrName == 'null') 
				{
					if (isFromSuperManager)
					{
						 verifying("egsm~!~");
					}
					else
					{
						 verifying("admin~!~");
					}
				}
			}
		}
	})(window);
	// Disabling the browser back button - ends here
</script>
<link rel="stylesheet" href="/final/styles/jscrollpane/jquery.jscrollpane.css"/>
<%
	if ((existingUser == null || 
		(existingUser != null && (existingUser.trim().length() == 0 || existingUser.equalsIgnoreCase("null"))))
		)
	{
		if (loginAuthentication || (!loginAuthentication && uName != null))
		{
%>
			<egui:loadApp baseDir="/final/scripts" appName="LoginApp"/>
<%
		}
	}
%>
</head>
<body>
</body>
</html>
<%
}
catch(Throwable th)
{
	System.out.println("-----Exception in egLogin.jsp--------------");
	th.printStackTrace();
}
%>

<%!
	protected String findAndReplaceString(String s,String s_search,String s_replace)
	{
		StringBuffer sb_tmp = new StringBuffer();
		while(s.indexOf(s_search) > -1)
		{
			sb_tmp.append(s.substring(0,s.indexOf(s_search)) + s_replace);
			s = s.substring(s.indexOf(s_search) + s_search.length(),s.length());
		}
		if(s.length() > 0)
			sb_tmp.append(s);
		return sb_tmp.toString();
	}
%>



