/**
 * WebLoginAtom JS 클래스 리스트
 * 
 * PQLogin
 * WebLoginAtom
 */

function PQLogin ()
{
}

PQLogin.URL = "/ups/Login.do";

PQLogin.login = function (strID, strPWD, strDepCode, nLoginType)
{
	var nKey = Utils.parseInt(PQAjax.post(PQLogin.URL + "?ServiceName=getKey", ""));
	//Base64로 변경된 문자 중에 '+'가 서블릿에서 사라지는 문제때문에 '-'로 변경해서 전송합니다.
	//TODO: 서블릿 오류 수정이 필요합니다.
	var strEncryptedPwd = Utils.replace(Utils.encrypt(strPWD, nKey), "\\+", "-");
	var strLoginQuery = "?ServiceName=login&pn=" + GetProjectName() + "&clk=" + GetCommonLoginKey() + 
		"&userId=" + strID + "&password=" + strEncryptedPwd + "&depCode=" +  strDepCode + 
		"&loginType=" + nLoginType + "&projectLicenseCode=" + GetProjectLicenseCode();
	if (is_mobile)
	{
		strLoginQuery += "&device=MOBILE&application=WEB";
	}
	else
	{
		strLoginQuery += "&device=PC";
	}
	var strResult = PQAjax.post(PQLogin.URL + strLoginQuery, "");
	
	return null != strResult && "Y" == strResult;
}

PQLogin.logout = function ()
{
	var strLoginQuery = "?ServiceName=logout"
	PQAjax.post(PQLogin.URL + strLoginQuery, "");
}

function HyperLinkValue (nRunType, strRunPath, strParameter, nLinkType, nWindowWidth, nWindowHeight, bHideToolbar)
{
	this.m_nRunType = nRunType;
	this.m_strRunPath = strRunPath;
	this.m_strParameter = strParameter;
	this.m_nLinkType = nLinkType;
	this.m_nWindowWidth = nWindowWidth;
	this.m_nWindowHeight = nWindowHeight;
	this.m_bHideToolbar = bHideToolbar;
}

HyperLinkValue.prototype.connectLink = function (bIsSuccess)
{
	if (Utils.isEmpty(this.m_strRunPath))
	{
		// 설정 안되었을 경우 처리
		if (bIsSuccess)
		{
			window.location.reload();
		}
	}
	else
	{
		WebConnectionModel.open(this.m_nRunType, this.m_strRunPath, this.m_nLinkType, 
					this.m_bHideToolbar, this.m_nWindowHeight, this.m_nWindowWidth, 
					this.m_strParameter, "");
	}
}


var g_objGlobalLoginAtom = null;	// 아톰 리스트를 생성하지 않고, 전역 객체 하나만 사용한다.

/**
 * 서버접속 아톰.
 * 솔루션 로그인 또는 포털 로그인을 처리합니다.
 */
function WebLoginAtom (strVarName, nScriptIndex, strLoginPath, strLogoutPath, strDepInfoList, nLoginType, 
						strIDVarName, strPassVarName, bSucessPrevPage, bShowFailMessage, 
						objSuccessHyper, objFailHyper, objLogoutHyper)
{
	this.m_strVarName = strVarName;
	this.m_nScriptIndex = nScriptIndex;
	
	this.m_strLoginPath = strLoginPath;
	this.m_strLogoutPath = strLogoutPath;
	this.m_strDepInfoList = strDepInfoList;		// 부문 정보 리스트 문자열
	this.m_nLoginType = nLoginType;
	
	this.m_heAtom = document.getElementById("__WEB_LOGIN_ATOM_" + strVarName);
	
	this.m_strIDVarName = strIDVarName;
	this.m_strPassVarName = strPassVarName;
	this.m_bSucessPrevPage = bSucessPrevPage;
	this.m_bShowFailMessage = bShowFailMessage;
	this.m_objSuccessHyper = objSuccessHyper;
	this.m_objFailHyper = objFailHyper;
	this.m_objLogoutHyper = objLogoutHyper;
}

WebLoginAtom.prototype.getVarName = function ()
{
	return this.m_strVarName;
}

WebLoginAtom.prototype.getScriptIndex = function ()
{
	return this.m_nScriptIndex;
}

/**
 * 초기화
 */
WebLoginAtom.prototype.init = function ()
{
	if (ModelCore.isSolutionLoggedin() || GlobalField.isPortalLoggedin())
	{
		this._changeBackgroundImage(true);
	}
}

WebLoginAtom.prototype.onClick = function ()
{
	if (ModelCore.isSolutionLoggedin() || GlobalField.isPortalLoggedin())
	{
		this._logout();
	}
	else
	{
		this.executeLogin();
	}
}

/**
 * 로그인을 수행한다.
 * @param strID ID.
 * @param strPassword 암호.
 */
WebLoginAtom.prototype.login = function (strID, strPassword)
{
	if (!this._login(strID, strPassword))
	{
		alert(Utils.LocalizedString("WebLoginAtom", "login_failed", new Array()));
	}
}


/**
 * 로그아웃을 수행한다.
 */
WebLoginAtom.prototype.logout = function ()
{
	this._logout();
}

/**
 * 아톰리스트에 추가
 */
WebLoginAtom.prototype.putAtom = function ()
{
	// 로그인 아톰은 하나만 사용되므로, 아톰 리스트를 생성하지 않고,
	// 전역객체에 바로 설정한다.
	g_objGlobalLoginAtom = this;
}

/**
 * 인자로 받은 값만큼 top을 변경시킨다
 * 
 * @param nRepositionValue (top 변경 값)
 */
WebLoginAtom.prototype.repositionYPos = function (nRepositionValue)
{
	var nTop = this.m_heAtom.offsetTop;
	
	this.m_heAtom.style.top = (nTop + nRepositionValue) + "px";
}

/**
 * 인자로 받은 값만큼 left를 변경시킨다
 * 
 * @param nRepositionValue (left 변경 값)
 */
WebLoginAtom.prototype.repositionXPos = function (nRepositionValue)
{
	var nLeft = this.m_heAtom.offsetLeft;
	
	this.m_heAtom.style.left = (nLeft + nRepositionValue) + "px";
}


////////////////////////////////////////////
// private method
//

/**
 * 배경 이미지를 변경한다.
 * @param bLogin 로그인 상태면 true.
 */
WebLoginAtom.prototype._changeBackgroundImage = function (bLogin)
{
	if (null != this.m_heAtom)
	{
		if (bLogin)
		{
			this.m_heAtom.style.backgroundImage = "url(" + this.m_strLogoutPath + ")";
		}
		else
		{
			this.m_heAtom.style.backgroundImage = "url(" + this.m_strLoginPath + ")";
		}
	}
}

/**
 * 로그인을 수행한다.
 * 아이디, 비밀번호 아톰의 변수명이 설정되어 있으면 해당 값을 가져와서 수행하고,
 * 없으면 로그인창을 띄워서 ID, Password를 입력받은 후 로그인을 한다.
 * 
 * 로그인 성공여부에 따라서 HyperLinkValue 값에 설정된 페이지로 이동한다.
 */
WebLoginAtom.prototype.executeLogin = function ()
{	
	var objResult;
	var objIDAtom = Model.getAtom(this.m_strIDVarName);

	// 로그인 정보를 만들어 반환합니다
	if (null == objIDAtom)
	{
		objResult = this._showLoginDialog();
		if (is_android || is_iphone) 
		{
			//로그인 다이얼로그에서 executeLogin4Mobile() 호출해서 처리.
			return;
		}
	}
	else
	{
		var strPass = Model.getAtomValue(this.m_strPassVarName);
		
		objResult = 
		{
			UserID : objIDAtom.getValue(),
			UserPWD : strPass
		};
	}
	
	if (this._isValidLoginInfomation(objResult))
	{
		this._executeLogin(objResult.UserID, objResult.UserPWD);
	}
}

WebLoginAtom.prototype.executeLogin4Mobile = function (userId, userPassword)
{	
	this._executeLogin(userId, userPassword);
}

WebLoginAtom.prototype._executeLogin = function (userId, userPassword)
{	
	if (this._login(userId, userPassword))
	{
		GlobalField.setWebLoginInProgress();
		
		if (this.m_bSucessPrevPage)
		{
			// 이전 페이지 이동
			var strPrevUrl = CookieLib.getCookie("_PQWebURL_");
			if (null != strPrevUrl && 0 < strPrevUrl.length)
			{
				var strRealPath = Utils.getPathString (strPrevUrl);
				
				strRealPath = encodeURI(strRealPath);
				
				if (GlobalField.isEmbededModel())
				{
					window.parent.location.href = strRealPath;
				}
				else
				{
					window.location.href = strRealPath;
				}
			}
		}
		else
		{
			if (null != this.m_objSuccessHyper)
			{
				// 성공시 페이지 이동
				this.m_objSuccessHyper.connectLink(true);
			}
			else
			{
				window.location.reload();
			}
		}
	}
	else
	{
		if (this.m_bShowFailMessage)
		{
			alert(Utils.LocalizedString("WebLoginAtom", "login_failed", new Array()));
		}
		
		// 실패시 페이지 이동
		this.m_objFailHyper.connectLink(false);
	}
}

/**
 * 로그인을 한다.   0:포털, 1:솔루션, 2:포털+솔루션
 * @param strID ID.
 * @param strPassword 암호. 
 */
WebLoginAtom.prototype._login = function (strID, strPassword)
{
	if (0 < this.m_nLoginType)
	{
		if (IsDotNet())
		{
			Model.startWaitMessage();
			var bResult = this._loginDotNet(strID, strPassword);
			Model.stopWaitMessage();
			
			if (bResult && 2 == this.m_nLoginType)
			{
				// 솔루션 로그인은 .net에서 수행되었으므로, portal 로그인만 수행한다. 
				bResult = PQLogin.login(strID, strPassword, this._makeDepInfoString(), 0);
				if (bResult)
				{
					this._handlePortal();
				}
			}
			
			return bResult;
		}
		else
		{
			if (PQLogin.login(strID, strPassword, this._makeDepInfoString(), this.m_nLoginType))
			{
				if (1 == this.m_nLoginType)
				{
					return this._handleSoultion();
				}
				else if (2 == this.m_nLoginType)
				{
					this._handlePortal();
					return true;
				}
			}
		}
	}
	else 
	{
		if (PQLogin.login(strID, strPassword, this._makeDepInfoString(), this.m_nLoginType))
		{			
			return true;
		}
	}
	
	return false;
}

/**
 * .net 솔루션에 로그인을 한다.
 * @param strID ID.
 * @param strPassword 암호. 
 */
WebLoginAtom.prototype._loginDotNet = function (strID, strPassword)
{
	var heWebBosClient = document.getElementById("__PQClient_DotNet");
	if (null != heWebBosClient)
	{
		var strResult = heWebBosClient.ServerConnectEx(strID, strPassword, "", GetProjectName());
		if ("Y" == strResult)
		{
			this._changeBackgroundImage(true);			
			
			if (ContainsInputDataAtom())
			{
				// 데이터입력란 아톰의 기본값을 가져오기 위해서.
				InputDataAtom.init();
			}
			
			if (ContainsWebSchedulerAtom())
			{
				WebSchedulerAtom.load();
				WebSchedulerAtom.setLoginInfo(strID, strPassword);
			}
			return true;
		}
	}
	
	return false;
}

/**
 * 솔루션 로그인 결과 처리
 */
WebLoginAtom.prototype._handleSoultion = function ()
{
	g_nSolutionLoginState = SOLUTION_LOGIN_NOGLOBAL;
	
	this._changeBackgroundImage(true);
		
	if (ContainsButtonAtom())
	{
		// 버튼의 권한 설정을 새로 하기 위해서.
		ButtonAtom.init();
	}
	
	if (ContainsInputDataAtom())
	{
		// 데이터입력란 아톰의 기본값을 가져오기 위해서.
		InputDataAtom.init();
	}
	return true;
}

/**
 * 포털 로그인을 결과 처리
 */
WebLoginAtom.prototype._handlePortal = function ()
{
	ModelCore.getPortalUserData();
	
	this._changeBackgroundImage(true);
	
	if (ContainsButtonAtom())
	{
		// 버튼의 권한 설정을 새로 하기 위해서.
		ButtonAtom.init();
	}
	
	if (ContainsInputDataAtom())
	{
		// 데이터입력란 아톰의 기본값을 가져오기 위해서.
		InputDataAtom.init();
	}
	
	this._webMenuInit();
}

WebLoginAtom.prototype._webMenuInit = function ()
{
	if (ContainsWebTreeMenuAtom())
	{
		WebTreeMenuAtom.init();
	}
	if (ContainsWebTabMenuAtom())
	{
		WebTabMenuAtom.init();
	}
	if (ContainsWebSlideMenuAtom())
	{
		WebSlideMenuAtom.init();
	}
	if (ContainsWebLinkMenuAtom())
	{
		WebLinkMenuAtom.init();
	}
	if (ContainsWebLabelMenuAtom())
	{
		WebLabelMenuAtom.init();
	}
	if (ContainsWebDropMenuAtom())
	{
		WebDropMenuAtom.init();
	}
	if (ContainsWebComboMenuAtom())
	{
		WebComboMenuAtom.init();
	}
}

/**
 * 로그아웃 한다.
 */
WebLoginAtom.prototype._logout = function ()
{
	if (0 == this.m_nLoginType)
	{
		this._logoutPortal();
	}
	else if (1 == this.m_nLoginType)
	{
		this._logoutSolution();
	}
	else if (2 == this.m_nLoginType)
	{
		this._logoutSolution();
		this._logoutPortal();
	}
	
	this.m_objLogoutHyper.connectLink(true);
}

/**
 * 솔루션에서 로그아웃 한다.
 */
WebLoginAtom.prototype._logoutSolution = function ()
{
	if (IsDotNet())
	{
		var heWebBosClient = document.getElementById("__PQClient_DotNet");
		if (null != heWebBosClient)
		{
			heWebBosClient.Logout();
		}
	}
	else
	{
		if (ContainsWebModelAtom())
		{
			WebModelAtom.allClose();
		}
		
		PQLogin.logout();
		
		g_nSolutionLoginState = SOLUTION_NOT_LOGIN;
		CookieLib.deleteCookie("_GlobalInfo_");
	}
}

/**
 * 포털에서 로그아웃 한다.
 */
WebLoginAtom.prototype._logoutPortal = function ()
{
	ModelCore.removePortalUserData();
	
	this._changeBackgroundImage(false);
	if (ContainsButtonAtom())
	{
		// 버튼의 권한 설정을 새로 하기 위해서.
		ButtonAtom.init();
	}
	
	if (ContainsInputDataAtom())
	{
		// 데이터입력란 아톰의 기본값을 가져오기 위해서.
		InputDataAtom.init();
	}
	
	// 메뉴에 권한 설정을 새로 하기 위해서
	this._webMenuInit();
	
	PQLogin.logout();
}

/**
 * 로그인 다이얼로그를 연다
 */
WebLoginAtom.prototype._showLoginDialog = function ()
{
	if (is_android || is_iphone)
	{
		return Utils.openWindow(
				"/ups/sys/html/support/LoginDialog.html", 1, false, 182, 350);
	}
	else
	{
		return Utils.showModalDialog(
			"/ups/sys/html/support/LoginDialog.html", null, 410, 390, 350, 182);
	}
}

/**
 * 바른 접속 정보인자 확인 합니다 
 * @param objUserLoginInfo (접속 정보 객체)
 */
WebLoginAtom.prototype._isValidLoginInfomation = function (objUserLoginInfo)
{
	if ('undefined' != typeof(objUserLoginInfo) && null != objUserLoginInfo)
	{
		if ("" == objUserLoginInfo.UserID)
		{
			alert(Utils.LocalizedString("WebLoginAtom", "input_id", new Array()));
			return false;
		}
		else
		{
			return true;
		}
	}

	return false;
}

/**
 * UPS 로그인을 위한 부문정보 리스트를 생성한다
 * "부문코드,부문코드,부문코드" <= , 로 부문된 문자열 형식이다
 */
WebLoginAtom.prototype._makeDepInfoString = function ()
{
	var alDepInfoList = this.m_strDepInfoList.split("@");
	
	var strDepInfoResult = "";
	
	for (var i = 0, nLen = alDepInfoList.length; i < nLen; i++)
	{
		var alDepInfo = alDepInfoList[i].split(",");
		
		strDepInfoResult += alDepInfo[0];
		
		if (i + 1 < nLen)
		{
			strDepInfoResult += ",";
		}
	}
	
	return strDepInfoResult;
}

WebLoginAtom.prototype.getProperty = function (wNameID, pvaArgs , pRetVal)
{
	switch (wNameID)
	{
		default : return StdCore.E_NOT_DEF_PROPERTY;
	}
}

WebLoginAtom.prototype.setProperty = function (wNameID, pvaArgs, pRetVal)
{		
	switch (wNameID)
	{
		default : return StdCore.E_NOT_DEF_PROPERTY;
	}
}

WebLoginAtom.prototype.action = function (nPropID, arArgs, objRetVal)
{
	switch (nPropID)
	{
		case 0: case 221:
		case 2: case 210:
		{
			return this.raw_Action(nPropID, arArgs, objRetVal);
		}
		case 1: case 420:
		{
			return StdCore.S_OK;
		}
		default:
			return StdCore.E_NOT_DEF_PROPERTY;
	}
}

WebLoginAtom.prototype.raw_Action = function (nNameID, arArgs, objRetVal)
{
	objRetVal.setValue (0);
	switch (nNameID)
	{
		case 0: case 221: // 접속
		{
			if (null == arArgs || 3 > arArgs.length)
			{
				WebLoginAtom.executeLogin();
			}
			else
			{
				var strLoginID = arArgs[1].toStringX();
				var strLoginPassword = arArgs[2].toStringX();
							
				WebLoginAtom.login(strLoginID, strLoginPassword);
				
				//throw "";	// 서버접속 아톰의 접속() 실행으로 인하여 이후 스크립트 수행을 중단합니다.";
			}
			break;
		}
		case 2: case 210: //절단()
		{
			WebLoginAtom.logout();
			
			throw "";	// 서버접속 아톰의 절단() 실행으로 인하여 이후 스크립트 수행을 중단합니다.";
		}
		default: 
			return StdCore.E_NOT_DEF_PROPERTY;
	}
}

WebLoginAtom.getAtom = function (strVarName)
{
	if (null != g_objGlobalLoginAtom && g_objGlobalLoginAtom.getVarName() == strVarName)
	{
		return g_objGlobalLoginAtom;
	}
	
	return null;
}

WebLoginAtom.onClick = function (strVarName, objEvent)
{
	g_objGlobalLoginAtom.onClick();
}

WebLoginAtom.init = function ()
{
	if (null != g_objGlobalLoginAtom)
	{
		g_objGlobalLoginAtom.init();
	}
}

WebLoginAtom.login = function (strLoginID, strLoginPassword)
{
	g_objGlobalLoginAtom.login(strLoginID, strLoginPassword);
}

WebLoginAtom.logout = function ()
{
	g_objGlobalLoginAtom.logout();
}

WebLoginAtom.executeLogin = function ()
{
	g_objGlobalLoginAtom.executeLogin();
}

WebLoginAtom.executeLogin4Mobile = function (userId, userPassword)
{
	g_objGlobalLoginAtom.executeLogin4Mobile(userId, userPassword);
}

/**
 * QPM 모델이 열릴 때 솔루션 로그인이 안 된 상태면 로그인을 할 수 있도록 함.
 */
WebLoginAtom.executeLogin4QPM = function ()
{
	g_objGlobalLoginAtom = new WebLoginAtom(
			"_qpmlogin", -1, "", "", "", 1, 
			"", "", false, true, 
			null, null, null);
	g_objGlobalLoginAtom.executeLogin();
}

