﻿/*
 * Single Sign On Sript file
 *
 * 작성자 : 한빛소프트 김성재 (zeru@hanbitsoft.co.kr)
 * 
 */

var logoutUrl = "/auth/logout.aspx";
var checkTokenUrl = "/auth/checktoken.aspx";
var redirectUrl = "http://www.hanbiton.com/home/error.aspx";


var ls_codebase = "http://login.hanbiton.com/cab/NLSnSSO.cab#version=1,2,0,0";
var ls_clsid = "377FF862-62E0-4f33-B6E5-F58E0BC0F209";

var ls_vistar_codebase = "http://login.hanbiton.com/cab/NLSnSSO_V.cab#version=1,2,0,0";
var ls_vistar_clsid = "377FF862-62E0-4f33-B6E5-F58E0BC0F209";

//trust site 등록 activex
var ts_vistar_codebase = "http://login.hanbiton.com/cab/TrustSite.cab#version=1,0,0,1";
var ts_vistar_clsid = "07BBFE34-8B6B-4C96-B965-C7C2878118D0";

var errorUrl = "/home/ssoerror.aspx";

var isVistar = false;
var ls = null;
var ts = null;

function CheckOS() {

	if(navigator.userAgent.indexOf('Win') != -1)
	{ 
		var Version;
		var temp = navigator.userAgent.split(";");
		
		for(i=0;i<temp.length;i++)
		{
			if(temp[i].indexOf('Win') != -1)
			{
				Version = temp[i];
			}
		}
		
		if(Version.indexOf('6.0') != -1)
		{
			var OpSys = "Vistar"; 			
			isVistar = true; 
		} else {
			var OpSys = "Windows Me or NT or 2000"; 
			isVistar = false;
		}
	}	
	
	return OpSys;
}



// Parent Ts Check And Ts Object Load
function LoadCheckParentTS()
{
	if (document.all["hanbitonts"] ) {
		ts = document.all["hanbitonts"];
	}

	if(ts == null)
	{
		if(parent != null && parent != this)
		{
			if(top.ts != null)
				ts = top.ts;
		}
		
	}
	
}



// Ts Object Load
function LoadHanbitOnTS() {

	CheckOS();
	LoadCheckParentTS();
	if (ts != null) {			
		return;
	} else {
		if(isVistar) 
		{			
			var str='<OBJECT id="hanbitonts" codebase="' + ts_vistar_codebase + '" classid="CLSID:' + ts_vistar_clsid + '" style="display:none"></OBJECT>';
			document.write(str);	
			ts = document.all["hanbitonts"];				
		}	
	}		
}


// Parent Ls Check And Ls Object Load
function LoadCheckParentLS() 
{
	if (document.all["hanbitonls"] ) {
		ls = document.all["hanbitonls"];
	}

	if(ls == null)
	{
		if(parent != null && parent != this)
		{
			if(top.ls != null)
				ls = top.ls;
		}
	}
}


// load
function LoadHanbitOnLS() {
	
	var str;
	CheckOS();
	LoadCheckParentLS();
	
	if (ls != null) {			
		return;
	} else {
		if(!isVistar) 
		{			
			str='<OBJECT id="hanbitonls" codebase="' + ls_codebase + '" classid="CLSID:' + ls_clsid + '" onerror="ActiveXError()" style="display:none"></OBJECT>';
			str += '<script language="JavaScript" for="hanbitonls" event="fnShutDownEvent()"> Notice(ls.fnGetAlmMsg()); </script>';
			str += '<script language="JavaScript" for="hanbitonls" event="fnRedirectionEvent()"> window.location = "' + redirectUrl + '" </script>';
			str += '<script language="JavaScript" for="hanbitonls" event="fnDupLoginEvent()"> DuplicateLogin(); </script>';
			str += '<script language="JavaScript" for="hanbitonls" event="fnRecvMsg(msg)"> RecieveMemoMsg(msg); </script>';
			str += '<script language="JavaScript" for="hanbitonls" event="fnSendMsgRsp(msg))"> SendMsgRsp(msg); </script>';					
		} else {
			str='<OBJECT id="hanbitonls" codebase="' + ls_vistar_codebase + '" classid="CLSID:' + ls_vistar_clsid + '" onerror="ActiveXError();" style="display:none"></OBJECT>';
			str += '<script language="JavaScript" for="hanbitonls" event="fnShutDownEvent()"> Notice(ls.fnGetAlmMsg()); </script>';
			str += '<script language="JavaScript" for="hanbitonls" event="fnRedirectionEvent()"> window.location = "' + redirectUrl + '" </script>';
			str += '<script language="JavaScript" for="hanbitonls" event="fnDupLoginEvent()"> DuplicateLogin(); </script>';
			str += '<script language="JavaScript" for="hanbitonls" event="fnRecvMsg(msg)"> RecieveMemoMsg(msg); </script>';
			str += '<script language="JavaScript" for="hanbitonls" event="fnSendMsgRsp(msg))"> SendMsgRsp(msg); </script>';							
		}	
		document.write(str);	
		ls = document.all["hanbitonls"];			
	}		
}


function ActiveXError() {
	// alert("한빛온에서 제공하는 서비스를 모두 이용하시려면 ActiveX를 받아야합니다");
}

// init
function InitHanbitOnLS() {

	try {
		if (ls != null) {
			var ret = ls.fnInitialize(0, 0);
			if (ret != 0) {
				window.location = axErrorUrl;
				return;
			}
			var hist = this.window.location + "";
			hist = hist.substr(0, hist.lastIndexOf("/"));
			ls.fnSetHistory(hist);
		}
	} catch (e) {
		// 설치되지 않음
	}
	
}

function timeOutMessage()
{
	var w = window.open("/MsgPopup/timeout.aspx", "HanbitON_TimeOut", "width=425,height=290,status=no,scrollbars=no");
	
	if(w != null)
		w.focus();
	else
		alert('장시간 서비스를 이용하지 않아 고객정보\n안전을 위해 자동 로그아웃 됩니다.\n다시 로그인 하시면 서비스를 이용하실 수 있습니다.');		
}



// 
// HanbitON - Notice
//
var notice = new Array();
var notice_index = 0;
var notice_count = 0;

// notice
function Notice(msg) {
	notice[notice_count++] = msg;
	notice_index = notice_count - 1;

	ShowNotice(notice_index);
}

function ShowNotice(idx) {
  var layer = '<div style="position:absolute; left:125px; top:27px; width:290px; height:98px; background:white;">';
  layer += notice[idx] + '</div><div style="position:absolute; left:187px;top:145px;width:61px;height:22px;cursor:hand;" onclick="HideNotice()"></div>';

	var divs = document.getElementById("ssoNoticeDivs");
	divs.innerHTML = layer;
	divs.style.top = (document.body.clientHeight - 178) / 2;
	divs.style.left = (document.body.clientWidth - 440) / 2;
	divs.style.display = '';
}

function HideNotice() {
	var divs = document.getElementById("ssoNoticeDivs");

	if (notice_index > 0) {
		notice_index--;
		ShowNotice(notice_index);
	} else {
		divs.style.display = 'none';
	}
}


//document.write('<div id="ssoNoticeDivs" style="position:absolute; left:0px; top:0px; width:440px; height:178px; z-index:1; background-image:url(/images/pop_layer.gif); display:none;"></div>');


// duplicate login process
function DuplicateLogin() {
  if(!isVistar)
	{
		var w = window.open("/Popup/duplogin_discon.aspx", "HanbitON_DuplLogin", "width=400,height=253,status=no,scrollbars=no");
	} else {
		LogoutProcess(0);
	}
	ls.fnResetToken();   
}



function RunSso() {	
	//alert("HanbitOn RunSSO()\nhanbitoninfo:" + getCookie(".hanbitoninfo") + "\nToken:" + getCookie("t") + "\nUserID:" + getCookie("UserID"));		
	try {
		if (ls != null) {
			if (ls.fnCheckToken()) {
			}
		} else  {
			// object 없음
		}
	} catch (e) {
		// 설치되지 않음
	}
	
	var varUserID = getCookie("UserID") ;
	
	if (varUserID == "")
	{
	    varUserID  = getCookie("HANBITON_SEARCH") ; 
	}
	
	if(getCookie("t") != "" &&  varUserID != "") 
	{
		wCheckToken(varUserID, getCookie("t"));
		
	} else {
	}	

}



// verify token when authorization
function VerifyToken(id) {	
	//alert("HanbitOn VerifyToken : " + id + "\n" + "TOKEN : " + getCookie("t"));
	try {
		if (ls != null) {
			if (ls.fnCheckToken()) {
			}
		} else  {
			// object 없음
		}
	} catch (e) {
		// 설치되지 않음
	}
	
	if(getCookie("t") != "" && id != "" ) {
		wCheckToken(id, getCookie("t"));	
	} else {
	   // 로그인 유지로 인한 강제로그아웃 : 2007.10.04 / jini
	    LogoutProcess(0);	
	}
}


// run Membership SSO
function RunSsoMember() {	
	var Token, Tokens;

	try {
		if (ls != null) {
			if (ls.fnCheckToken()) {
				Token = ls.fnGetToken();
				Tokens = Token.split("|");

				if (Tokens[1] != "ERROR" && Tokens[0] != "") {
				
					if(document.Reg_Form.Tokens != null)
					{
						document.Reg_Form.Tokens.value = Tokens[1];
					}
					else
					{
						window.location = checkTokenUrl + "?u=" + Tokens[0] + "&r=" + window.location + "&t=" + Tokens[1];
					}
					
				}
				else
				{
					alert("다시 로그인 하여 주십시요.");
					window.location.href = "http://member.hanbiton.com/h_member/h_hms/ms_login.aspx?ReturnUrl=" + window.location; 
				}
			}
			else
			{
				alert("다시 로그인 하여 주십시요.");
					window.location.href = "http://member.hanbiton.com/h_member/h_hms/ms_login.aspx?ReturnUrl=" + window.location; 
			}
		} else  {
			// object 없음
		}
	} catch (e) {
		// 설치되지 않음
	}
}


// set token
function SetToken(userId, token) {
	if(getCookie("t") == "")
	{  
		document.cookie = "t" + "=" + escape( token ) + "; path=/;";
	}
}


// 쪽지 보내기
function SendMemoMsg(msg) {
	/*
	try {
		//if (ls) {
		if (ls && !isVistar) {
			ls.fnSendMsg(msg);
		} else  {
			// object 없음
			alert('SSO ActiveX가 생성되지 않았습니다');
		}
	} catch (e) {
		// 설치되지 않음
	}
	*/	
}

var ReceiveMessage;
// 쪽지 받아서 보여주기
function RecieveMemoMsg(msg) 
{
	/*
	var LeftPosition = 0;//(screen.width) ? (screen.width-300)/2 : 0;
	var TopPosition = 0;//(screen.height) ? (screen.height-100)/2 : 0;
	
	var settings='width=335,height=300,top='+TopPosition+',left='+LeftPosition ;
	
	if (msg != null && msg != ''){
		var kind_of_msg = msg.split("|");

		//선물 쪽지 관련 블록 -------------------------- 코너스톤 2005.7.9
		
		if (parseInt(kind_of_msg[0]) == 6) {
			var Recv_cd_user = kind_of_msg[5]; //수신자 cd_user
			var cd_paper = kind_of_msg[1]; //cd_paper
			var cd_goods = kind_of_msg[11];
			var settings_gift ='width=385,height=400,top='+TopPosition+',left='+LeftPosition ;
		   
		   var win = window.open("http://www.hanbiton.com/shop/bric/Paper_RecvGift.aspx?r_cd_user=" + Recv_cd_user  + "&cd_paper=" + cd_paper + "&cd_goods=" + cd_goods,"",settings_gift);
		   win.focus();
		}
		//선물 쪽지 관련 블록 --------------------------		
		else {
			if (1 <= parseInt(kind_of_msg[0]) <= 3 || 7 <= parseInt(kind_of_msg[0]) <= 14) {
				var win = window.open("http://www.hanbiton.com/h_note/realnote.aspx?op=on&userid=" + kind_of_msg[5] + "&paper=" + kind_of_msg[1] + "&type=" + kind_of_msg[0] + "&up=0" ,"",settings);
				win.focus();
			}
		}
	}
	*/	
}

function SendMsgRsp(msg)
{
	/*
	var kind_of_msg = msg.split("|");
	if (parseInt(kind_of_msg[0]) == 1 || parseInt(kind_of_msg[0]) == 2) {
	} 
	*/	
}



function setcookie( name, value, expiredays ){
    var todayDate = new Date();
    todayDate.setDate( todayDate.getDate() + expiredays );
    document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
    //document.cookie = name + "=" + escape( value ) + "; path=" + "/hanbiton" + "; expires=" + todayDate.toGMTString() + ";"
}
	

function getcookie( name )
{	
   var nameOfCookie = name + "=";
   var x = 0;
   while ( x <= document.cookie.length ){
        var y = (x+nameOfCookie.length);
        if ( document.cookie.substring( x, y ) == nameOfCookie ) {
             if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
                  endOfCookie = document.cookie.length;
             return unescape( document.cookie.substring( y, endOfCookie ) );
        }
        x = document.cookie.indexOf( " ", x ) + 1;
        if ( x == 0 )
            break;
    }
	return "";
}



/*
function goActiveCheckToken(userId, targeUrl, sUrl)
{
	var token = getCookie(".HANBITON_TOKEN");
	//alert("goActiveCheckToken ==>" +token);
	var frm = document.Form1;
	
	frm.appendChild(document.createElement("<input type='hidden' name='u' value='" + userId + "'>"));
	frm.appendChild(document.createElement("<input type='hidden' name='t' value='" + token + "'>"));
	frm.appendChild(document.createElement("<input type='hidden' name='r' value='" + targeUrl + "'>"));
	
	frm.method = "post";
	frm.target = "_blank";
	frm.action = sUrl;
	frm.submit();	
	
	location.href = window.location;

}	
*/

