var SESSIONID_APPLET="20fcb85b-7e3e-4890-ab22-94e3afdef6dd";

function login_error_handler(msg,mascot_file_num)
{
  msg = msg.replace(/TAGLEFT;/g,"<");
	msg = msg.replace(/<br>/g,"\n");

  login_error_redirect(msg, mascot_file_num);
}

function login_error_redirect(msg, fnum)
{
  if (typeof $('#fo_error')[0] != 'undefined') {
    $('#fmsg').val(msg);
    $('#fnum').val(fnum);
    $('#pageUrl').val(document.location.href);
    $('#fo_error').submit();
  } else {
    alert (msgg);
  	showloginform();
  }
}

function multilogin_handler(usrid,killmescript,killmeurl)
{
  msg       = usrid+"님은 이미 피망 또는 세이클럽에 접속해있습니다. 기존 접속을 종료하시겠습니까?";
  SayDialog = confirm(msg);
    
  if (1 == SayDialog) {
  	eval(killmescript);
		//window.open(killmeurl);
	  try_login(usrid);
  }
  else 
  	showloginform();
}

function login_handler2(result)
{
  result=SayControl.codec(50,result,"");
  eval(result);
}

var saycontrol_upgraded=0;

function upgrade_saycontrol()
{
  if(saycontrol_upgraded)return;
  if(typeof(document.SayControlHelper)=="undefined")return;
  if(typeof(document.SayControlHelper.sessionversion)=="undefined")return;

  if(document.SayControlHelper.sessionversion>=sayctl_version)return;

  if(document.SayControlHelper.externalmethod("install",SESSIONID_APPLET,0,0,"접속 프로그램 업그레이드"))
  {
    saycontrol_upgraded=1;
  }
}

///////////////////
function login_message_handler(msg,mascot_file_num, loginform, result)
{
 if(loginform == 1)
 	showloginform();
}
////////////////////////

function login_handler_sayr(result)
{
  login_handler(result);
}

function login_handler(result,key,ip,port,cip,macaddress,uuid,gwmacaddress,mac2)
{
  if(result=="currentalready")
  {
    login_message_handler("다른 브라우저 창에 해당 아이디로 이미 로그인 중입니다.","02",1, result);

    try {
      if (document.fo_login.conntype[2].checked) // if paran sso (partner사 추가시 수정필요)
        document.location = 'http://saypmang.paran.com';
    }catch(e){}
    
    if(typeof(document.fo_login.sessid) != "undefined")
    	document.location.href = document.fo_login.pageurl.value;

    return;
  }

  if(result=="anotheralready")
  {
    login_message_handler("접속 오류입니다.","05",1);
    return;
  }

  if(result=="dualconnected")
  {
    if(typeof(post_login_script) != 'undefined')
    {
      eval(post_login_script);
    }
		
		if(pageurl.indexOf('istachy=1') < 0 )
    {
      if (pageurl.indexOf("?") < 0)
        pageurl += "?istachy=1";
      else
        pageurl += "&istachy=1";
    }

    window.open(pageurl,"_top");
    return;
  }

  if(result=="abused")
  {
    login_message_handler("이 PC는 폴리스에 의해 일시 접속이 제한됩니다.\n잠시 후(최장 30분) 다시 접속을 시도해 주시기 바랍니다.","05",1);
    return;
  }

  if(result=="excessconnect")
  {
    login_message_handler("동일한 PC에서 다수의 아이디로 동시에 로그인 하실 수 없습니다.","05",1, result);
    return;
  }

	if(result == "push_login_invalid_handle" || result == "push_login_not_idle" || result == "push_login_fail_irc_connect") {
		login_message_handler("세이클럽에 접속중인 아이디를 로그아웃 하신 후\n이용해 주시기 바랍니다.");
		return;
	}
	
  if(result!="connected")
  {
    if (result != "notreg")
    {
      login_message_handler("알수 없는 오류가 발생했습니다.","05",1);
      return;
    }
  }
  
  var bSSO = false;
  var bSSON = false;
  var bSecureConnect = false;

  if(typeof(document.fo_login.conntype)!="undefined")
  {
    if (typeof(document.fo_login.conntype.length)!="undefined")
    {
      if (document.fo_login.conntype.length >= 3 && document.fo_login.conntype[2].checked && document.fo_login.conntype[2].value == 3)
        bSSO = true;

      if (document.fo_login.conntype.length >= 4 && document.fo_login.conntype[3].checked && document.fo_login.conntype[3].value == 4)
          bSSON = true;

      
      if( (document.fo_login.conntype[1].checked && document.fo_login.conntype[1].value == 2) || bSSO  || bSSON )
        bSecureConnect = true;
    }
    else
    {
      if (document.fo_login.conntype.value == 3)
        bSSO = true;

      //if( (document.fo_login.conntype.checked && document.fo_login.conntype.value == 2) || bSSO )
      if( (document.fo_login.conntype.checked && document.fo_login.conntype.value == 2))
        bSecureConnect = true;
    }
  }

  if (bSecureConnect)
    login_url="https://secure.sayclub.com/global/login.nwz";
  
  var temp = typeof(document.fo_login.admin_index);
  if (temp == "undefined" || temp == "unknown")
    admin_index = 0;
  else
    admin_index = document.fo_login.admin_index.value;

  postdata
      ="usrid="+SayControl.codec(0,document.fo_login.usrid.value,"")
      +"&passwd="+SayControl.codec(0,document.fo_login.passwd.value,"")
      +"&pageurl="+SayControl.codec(0,document.fo_login.pageurl.value,"")
      +"&from="+SayControl.codec(0,document.fo_login.from.value,"")
      +"&key="+key
      +"&myip="+ip
      +"&myport="+port
      +"&admin_index="+admin_index
      +"&clientip="+cip
      +"&macaddress="+macaddress
      +"&gwmacaddress="+gwmacaddress
      +"&uuid="+uuid
      +"&mac2="+mac2
      +"&page_domain=sayclub.com"
      ;

  if (typeof(document.fo_login.iscapslock) == "object")
      postdata += "&iscapslock="+SayControl.codec(0,document.fo_login.iscapslock.value,"");

  if (bSSO)
  {
    postdata += "&sso="+(bSSO ? '1' : '0');
    if(typeof(document.fo_login.ev) != 'undefined') postdata += "&ev=" + document.fo_login.ev.value;
    if(typeof(document.fo_login.cv) != 'undefined') postdata += "&cv=" + document.fo_login.cv.value;
    
    if(typeof(document.fo_login.from_user_id) != 'undefined') {
    	postdata += "&channel_userid="+SayControl.codec(0,document.fo_login.from_user_id.value,"");
    	postdata += "&channel_id="+SayControl.codec(0,document.fo_login.from_site.value,"");
    	postdata += "&channel_srl="+SayControl.codec(0,document.fo_login.from_msrl.value,"");
    	postdata += "&chkey="+SayControl.codec(0,document.fo_login.chkey.value,"");
    }
  } 
  if (bSSON)
  {
    postdata += "&sso="+(bSSON ? '1' : '0')
     +"&fingerprint="+SayControl.codec(0,document.fo_login.fingerprint.value,"")
     +"&timestamp="+SayControl.codec(0,document.fo_login.timestamp.value,"");
  } 

	if(typeof(document.fo_login.sessid) != "undefined")
		postdata += "&sessid=" + document.fo_login.sessid.value;
	
  if( eval("document.fo_login.popupurl") != null ) postdata += "&popupurl="+document.fo_login.popupurl.value;
  if( eval("document.fo_login.popupoption") != null ) postdata += "&popupoption="+document.fo_login.popupoption.value;

  SayControl.executeHTTP(login_url,postdata,"login_handler2","");
}

function saycontrol_error()
{ 
	/*
	if(typeof(Util) == 'object' && typeof(Util.urlencode) == 'function'){
		var origin_url = Util.urlencode(Util.urlencode(document.location.href));
 	}else{
		var origin_url = "http://www.sayclub.com";
	}
	
  var from = 'sayclub';
	document.location.href = "http://www.sayclub.com/install_control.nwz?origin="+origin_url+"&from="+from;
 	return;
 	*/
}

var cntRetry = 0;
function try_login(usrid)
{
  if(typeof(SayControl.sessionversion)=="undefined")
    saycontrol_error();

  if (cntRetry > 10)
    saycontrol_error();

  if(SayControl.readyState!=4)
  {
    if ("undefinded" != typeof(usrid) && "unknown" != typeof(usrid))
    {
      var cmd = "try_login('"+usrid+"')";
      setTimeout(cmd,100);
      cntRetry++;
    }
    return 0;
  }

  sessiontype=typeof(SayControl.sessionversion);
  if(sessiontype!="undefined")
  {
    if(usrid.search(/[ㄱ-ㅎ|ㅏ-ㅣ|가-힝]/) != -1) 
    {
      login_message_handler("등록되지 않은 사용자 입니다. \n정확한 영문아이디를 입력하여 주십시요.","05",1);
      return;
    }

    usrid = usrid.replace(/\s/g, '');
    set_saycontrol(document.SayControl);
    var err = SayControl.login(usrid,usrid);
    if(err <= 0)
    {
      if(err == -44) {
      	login_message_handler("세이클럽에 접속중인 아이디를 로그아웃 하신 후\n이용해 주시기 바랍니다.");
      }
      else {
      	login_message_handler("로그인 컨트롤에서 오류가 발생했습니다.\n에러코드: " + (-err),"05",1);
      }
    }
  }
  else 
  {
    saycontrol_error();
  }
}

function enable_saycontrol()
{
  span=document.frames["span_sayctl"];
  if(typeof(span)=="undefined")
  {
    document.body.insertAdjacentHTML("afterBegin",'<span id="span_sayctl" style="display:none"></span>');
  }
  
  span=document.frames["span_sayctl"];
  span.innerHTML='';
  var text='<object id=SayControl name=SayControl classid="clsid:'+sayctl_classid+'" codebase="'+SSLHandler.getSSLResourceURL(sayctl_codebase)+'"></object>';
  span.innerHTML=text;
}

function start_login(usrid)
{
  upgrade_saycontrol();
  enable_saycontrol();
  try_login(usrid);
}

function fo_finish (IsKbd)
{
  if(IsKbd && event)
    event.returnValue = false;
  
  if (0 == document.fo_login.usrid.value.length || 0 == document.fo_login.passwd.value.length)
  {
    if (typeof(loginLayer) == "object" && typeof(loginLayer.handleFocus) == "function")
      loginLayer.handleFocus();
    else
      document.fo_login.usrid.focus();
    login_message_handler("아이디와 비밀번호를 입력해 주세요.","02",0);
    return;
  }

//  document.fo_login.passwd.disabled=true;
//  document.fo_login.usrid.disabled=true;
//  start_login(document.fo_login.usrid.value);

  if (navigator.userAgent.indexOf('MSIE')>-1 && navigator.userAgent.indexOf("Windows CE")<0) {
       document.fo_login.passwd.disabled=true;
       document.fo_login.usrid.disabled=true;
       start_login(document.fo_login.usrid.value);
  } else document.fo_login.submit();
}

function ssl_window()
{
  var wndNew = window.open ('http://www.sayclub.com/ssl_message.nwz','ssl_window','width=560,height=450,toolbar=no,location=no');
  if (wndNew) {
    wndNew.focus();
  }
}

function showloginform()
{
  if(typeof(document.fo_login) != 'undefined')
  {
    if( typeof(document.fo_login.usrid) != 'undefined' &&  document.fo_login.usrid.type != 'hidden')
    {
      if (typeof(LoginPage) != "undefined")
        LoginPage.style.display="none";

      document.fo_login.passwd.disabled=false;
      document.fo_login.usrid.disabled=false;
      document.fo_login.passwd.value="";
      document.fo_login.usrid.select();
      document.fo_login.usrid.focus();
    }   
  }  
}

var tmpCapsLock = false;
function checkCapsLock(e)
{
  var myKeyCode=0;
  var myShiftKey=false;

  if ( document.all )
  {
    myKeyCode=e.keyCode;
    myShiftKey=e.shiftKey;
  }
  if (e.keyCode != 13 && tmpCapsLock == false)
  {
    if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey )
    {
      tmpCapsLock = true;
      document.fo_login.iscapslock.value = 'Y';
    }
    else if ( ( myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey )
    {
      tmpCapsLock = true;
      document.fo_login.iscapslock.value = 'Y';
    }
    else
    {
      tmpCapsLock = false;
      document.fo_login.iscapslock.value = "N";
    }
  }
}

//비밀번호,아이디 찾기 창띄우기
function openPasswdFinder()
{
  PopupHandler.openWin(SSLHandler.sslRequestUrl("https://www.sayclub.com/forget_passwd.nwz"), "passwd_window", '400','275');
}

function openAccessHelper()
{
  PopupHandler.openWinScroll('http://mm.sayclub.com/sayclub/home/help_access.html', '_helpAccess', 517, 600);
}
