﻿/*
본문 하단에 있는 저작권 문구 목록
A : 연합기사
F : 외국어기사
H : 한민족 기사
*/
var COPYRIGHT = {    
    'A':"<p><span class='w_245'>저작권자(c)<strong>연합뉴스</strong>. 무단전재-재배포금지</span></p>",
    'F':"<p><span class='w_215 eng_copy'>Copyright(c)<strong>YonhapNews</strong>. All rights reserved.</span></p>",
    'H':"<p><span class='w_290'>저작권자(c)<strong>해당 동포언론사</strong>. 무단전재-재배포금지</span></p>"
    };

/*
header, footer 파일 경로
*/
var COMMON = {
    footer:"../Common/footer.htm",
    header:"../Common/header.htm",
    header2:"../Common/header2.htm"
    };

/*
템플릿 HTML 들 정보를 refresh
개발 중에 항상 갱신하기 위해 설정함
OPEN후 제거 예정
*/    
$clearFile("../Common/collector.aspx");
var TEMPLATE = $doc("../Common/collector.aspx");


var LoginFunction = {};


/*
팝업 변수
*/
var popWin;

/*
해바라기에서 디자인한 HTML에 항상 들어가 있는 함수들 MM_~~~
*/
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}




/*
템플릿을 반환한다.
collector.aspx 에 포함되지 않는 것은 서버에서 직접 읽어 온다.
*/
function $template(url)
{
    try
    {
        var url2 = url.toUpperCase();
        url2 = url2.replace(/^.*\//, '');
        
        var t = $nt(TEMPLATE, "/TemplateList/" + url2);    
        if (t)
        {
            return t;
        }
        else
        {
            return $txt(url);
        }
    }catch(e)
    {
        $debug('$template:url[' + url + ']-' + e);
    }
    return "";
}
// format 이 없으면 날짜 형식 YYYY MM DD hh:mm
function makeDate(dd, format)
{
    try
    {
        if (!dd)
            return "";
        if (!format)
            return dd.substring(0,4) + " " + dd.substring(4,6) + " " + dd.substring(6,8) + " " + dd.substring(8,10) + ":" + dd.substring(10,12);
            
        var d = format;
        if (dd.length > 3)
        {
            d = d.replace(/%Y/g, dd.substring(0,4));
            d = d.replace(/%y/g, dd.substring(2,4));
        }    
        if (dd.length > 5) 
            d = d.replace(/%M/g, dd.substring(4,6));
        if (dd.length > 7)    
            d = d.replace(/%d|%D/g, dd.substring(6,8));
        if (dd.length > 9)
            d = d.replace(/%H|%h/g, dd.substring(8,10));
        if (dd.length > 11)    
            d = d.replace(/%m/g, dd.substring(10,12));
        if (dd.length > 13)    
        d = d.replace(/%s|%S/g, dd.substring(12, 14));
        return d;
    }catch(e)
    {
        $debug('makeDate:dd[' + dd + '] format[' + format + '] - ' + e);
    }
    return "";
}

// 날짜 형식 MM.DD hh:mm  
function makeTDate(dd)
{
    return dd.substring(4,6) + "." + dd.substring(6,8) + " " + dd.substring(8,10) + ":" + dd.substring(10,12);
} 
function makeSDate(dd)
{   
    return dd.substring(2,4) + "." + dd.substring(4,6) + "." + dd.substring(6,8);
}  
//본문 글씨 크기 조정
//HTML의 contentsBody 에 미리 font-size 가 설정되어 있어야지만 사용 가능함 
//css 에 선언되어 있는 것은 처리 안됨 
function fontSize(val, id)
{   
    try
    {
        var ele = $(id)
        if (!id)
            ele = $('contentsBody');
        if (ele)
        {
            var ss = ele.style.fontSize;
            var size = parseInt(ss.replace(/^([0-9]+).*/,"$1"));
            var unit = ss.replace(/[0-9]+/,'');
            
            if (val == '+')
                ele.style.fontSize= (size+1) + unit;
            else
                ele.style.fontSize= (size-1) + unit;
        }
    }catch(e)
    {
        $debug('fontSize:val[' + val + '] id[' + id);
    }
    
}
// 썸네일이미지 경로 
function T(path)
{
    return imagePath(path,'T');
}
// P2 이미지 경로
function P2(path)
{   
    return imagePath(path,'P2');
}
// P1 이미지 경로
function P1(path)
{
    return imagePath(path, 'P1');
}    

// 이미지 경로 생성
function IMG(path)
{
    if (!path || path.length == 0)
        return "";
    if (/^http:/i.test(path))
        return path;
 
    path = path.replace(/\/\//g, '/');
               
    if (/.*data_?file.*/.test(path))
    {
        if (path.charAt(0) == '/')    
            return '..' + path;
        else
            return '../' + path;    
    }
    else
    {
        return T(path);
    }
}    
// 이미지 경로 생성    
function imagePath(path,type)
{
    if (!path)
        return "";        
    if (/^http.*/i.test(path))
        return path;        
    if (!type)
        type = 'T';
    
    
    path = path.replace(/\/\//g, '/');
    if (/.*data_?file.*/.test(path))
    {
        //$debug('origin:' + path);
        path = path.replace(/[Cc]ontents\//, '');  
        
        // 영상은 그대로
        if (!/.*mpic.*/i.test(path))
        {
            path = path.replace(/(_T|_P[0-9])/g, '');
            path = path.replace(/.(jpg|gif)$/i, '_' + type + ".$1");
        }
        //$debug(path);
        if (path.charAt(0) == '/')    
            return '..' + path;
        else
            return '../' + path;    
    }
    else
    {
        //path = path.replace(/.jpg/i, '_' + type + '.jpg');
        path = path.replace(/^\/?[Cc]ontents\//, '');   
        path = path.replace(/_T|_P[0-9]/, '');
        if (/.*AKR.*/.test(path))
            path = 'http://img.yonhapnews.co.kr/' + path;
        else
            path = 'http://img.yonhapnews.co.kr/' + path.replace(/.(jpg|gif)$/i, '_' + type + '.$1');
        return path;
    }
}

// 이미지 swap
// *.gif, *_on.gif 에 해당하는 것에만 동작
function imgSwap(id,on)
{
    var e = $(id);
    if (e && e.tagName == 'IMG')
    {
        var url = e.src;
        if (on)        
        {
            if (!/.*_on.gif$/.test(url))
                e.src = url.replace(/.gif/, '_on.gif');
        }    
        else 
        {
            if (/.*_on.gif$/.test(url))
                e.src = url.replace(/_on.gif/, '.gif');            
        }    
    }
}
// 주석문 삭제 json 변환 전 사용.
function removeComment(txt)
{
    return txt.replace(/<\!--[^>]*-->/g, '');
}
// json 변환
function $json(txt)
{
    if ($cookie('CLS') == 'S')
    {
        try
        {
            return eval('(' + removeComment(txt) + ')');
        }catch(e)
        {
            
            if (confirm('JSON 데이터 파싱에 실패했습니다. 원본을 보시겠습니까?'))        
                alert(txt);
            return null;
        }
    }    
    else
    {
        //return eval('(' + txt + ')');
        return eval('(' + removeComment(txt) + ')');
    }
    
}
// ajax 의 history back 구현할때 사용
// fname 은 호출할 function 명
// param 은 파라미터의 Array, 하나일때는 string 으로 입력 가능
function goPage(fname,param)
{   
    var func = fname;
    if (!param)
        func += "()";
    else if (typeof param != 'object')
        func += "(\"" + param + "\")";
    else
    {
        func += "(";
        for (var i=0; i<param.length; i++)
        {
            if (i>0)
                func += ",";
            if (param[i])
                func += "\"" + param[i] + "\"";
            else
                func += "\"\"";    
        }
        func += ")";
    }
    var url = '../common/r.aspx?script=' + encodeURIComponent(func);
    var historyDiv = $('__hiddenFrame__');
    if (!historyDiv)
    {
        historyDiv = document.createElement('IFRAME');
        historyDiv.id = '__hiddenFrame__';
        historyDiv.style.display = 'none';
        document.body.insertBefore(historyDiv, null);
    }
    var doc = historyDiv.contentWindow.document;
    doc.location = url;
    //historyDiv.src = url;
    
}


// 한민족 포털화면의 좌측 바를 조절
function checkLayout()
{
    if (!$('bodyWrap'))
        return;
        
    var w = parseInt(window.document.body.clientWidth);
    //var ele = document.getElementById('wrap_out');    
    if (w < 1024)
    {   
        $('bodyWrap').className = 'bodyWrap_no';
    }
    else
    {
        $('bodyWrap').className = '';
    }
}
/**
본문에서 내장사진을 추출함 (첫번째 사진)
*/
function $inner(body)
{
    body = body.replace(/<YNAPHOTO path/gi, '<img src');
    if (/^[\s\S]*<img src=['\"]([^'\"]+)['\"][\s\S]*$/i.test(body))
        return body.replace(/^[\s\S]*<img src=['\"]([^'\"]+)['\"][\s\S]*$/i, "http://img.yonhapnews.co.kr/$1").replace("contents/", "");        
    else
        return '';
}
function $modTable(body)
{   
    if (/rowspan|colspan/i.test)
    {
        body = body.replace(/(rowspan=|colspan=)([0-9]+)/gi, "$1'$2'");
        body = body.replace(/(width=|height=)([0-9]+)/gi, "$1'$2px'");
        body = body.replace(/rowspan=['\"]?0['\"] /gi, '');
        body = body.replace(/colspan=['\"]?0['\"] /gi, '');
        body = body.replace(/(width=|height=)['\"]([0-9]+)['\"]/gi, "$1'$2px'");
        //body = body.replace(/(<table)/ig, '<center>$1');
        //body = body.replace(/(\/table>)/ig, '$1</center>');
        return body;
        //return body.replace(/rowspan=['\"]?0['\"]?|colspan=['\"]?0['\"]?/gi, '');
    }
    return body;
}
function $removeImage(body)
{
    var b = body.replace(/<(img|ynaphoto) [^>]+./gi, '').replace(/^\\s*/,'');       
    if (/.*(<|&lt;)table [\s\S]*/i.test(b))
    {
        b = b.replace(/(<|&lt;)table[\s\S]+$/i, '<표 기사입니다>');
    }
    return b;
}
function $relation(cid)
{
    if (cid != null && /^AKR.*/.test(cid))
    {
        var url = "../News/contents.aspx?json=1&relation=1&cid=" + cid;
        $clearFile(url);
        var t = $txt(url);
        return $json(t);    
    }
    return {};
}
function $divlist(cid)
{
    var url = "../Code/code.aspx?json=1&codetype=DivLink&cid=" + cid;
    var t = $txt(url);
    return $json(t);
}
/**
본문정보를 가져옴 (JSON)
relation가 있으면 관련기사를 포함함.
page가 있으면 해당 기사가 포함된 페이지를 포함함.
*/
function $contents(cid,page,refresh)
{
    var url = "../News/contents.aspx?json=1&cid=" + cid;
    // page 찾기는 하지 않음 20100426 ; 과거 기사일경우 로딩 속도가 너무 김
    //if (page)
    //    url += "&page=1";
    if (refresh)
        url += "&refresh=1";    
    $clearFile(url);
    var t = $txt(url);
    var js = $json(t.replace(/&apos;/g, "'"));    
    if (!js["DATA"])
    {
        alert('기사번호 ' + cid + ' 의 데이터를 DB에서 찾을 수 없습니다.');
        return js;
    }
    if (js["DATA"] && js["DATA"][0] && js["DATA"][0]["BODY"])
    {
        //if (js["DATA"][0]["TITLE"] && cid.charAt(0) != 'O')        
        //    js["DATA"][0]["BODY"] = $body(js["DATA"][0]["TITLE"], js["DATA"][0]["BODY"]);
        js["DATA"][0]["INNER"] = $inner(js["DATA"][0]["BODY"]);    
        js["DATA"][0]["BODY"] = $modTable(js["DATA"][0]["BODY"]);
        
    }
    return js;
    
}
function $embed(json)
{
    var data = json;
    if (json["DATA"])
        data = json["DATA"][0];
    if (!data)
        return "";
                
    var cid = (typeof json == 'string' && json.length == 20) ? json : data["CONTENTS_ID"];
    var ctype = cid.charAt(0);
    if (/^O.*/.test(cid))
    {
        ctype = cid.charAt(17) == 'K' ? 'A' :
            cid.charAt(17) == 'P' ? 'P' :
            'M';
    }
    if (ctype != 'M')
        return "";
        
    var embed = "";    
    if (/^M.*/.test(cid))
    {
        embed = $template('../Search/embed.htm');
        embed = embed.replace(/__CID__/g, cid);
        embed = embed.replace(/__YYYYMM__/g, cid.substring(3,9));        
    }
    else
    {
        
        embed = $template('../Search/embedf.htm');
        embed = embed.replace(/__PATH__/g, encodeURIComponent(data["FLASH"]));
        embed = embed.replace(/__IMAGE__/g, encodeURIComponent(data["IMAGE"].replace(/_s_/, '_b_')));        
    
    }    
    return embed;
}
function $list(json)
{
    var data = json;
    if (json["DATA"])
        data = json["DATA"];
    var a;    
    if (data.length == 0)
        return;
    if (!data[0]["TITLE"] || !data[0]["BODY"])
        return;
    
    for (var i=0; i<data.length; i++)
    {
        a = data[i];        
        data[i]["BODY"] = a["BODY"].replace(/^\s*|\s*$/g, '');
        data[i]["BODY"] = a["BODY"].replace(/^<br\/?>(<br\/?>)?/, '');
       
        //if (data[i]["CONTENTS_ID"][0] != 'O')
        //{
        //    data[i]["BODY"] = a["BODY"].replace(/^\s*|\s*$/g, '').replace(/^[^\n]+\n+/, '');          
        //}
        data[i]["BODY"] = data[i]["BODY"].replace(/&nbsp;/gi, '');
        data[i]["INNER"] = $inner(data[i]["BODY"]);
        data[i]["BODY"] = data[i]["BODY"].replace(/<(img|ynaphoto)[^>]+>/gi, '');
        data[i]["BODY"] = data[i]["BODY"].replace(/\s*<br\/?>\s*<br\/?>\s*<br\/?>/gi, '<br/>');
        data[i]["BODY"] = data[i]["BODY"].replace(/\s*<br\/?>\s*<br\/?>/gi, '<br/>');
        data[i]["BODY"] = data[i]["BODY"].replace(/^\s*<br\/?>/i, '');
        
        data[i]["BODY"] = data[i]["BODY"].replace(/<([a-zA-Z])/g, '&lt;$1');
        //data[i]["BODY"] = data[i]["BODY"].replace(/&lt;table/ig, '<TABLE');
        //data[i]["BODY"] = data[i]["BODY"].replace(/&lt;td/ig, '<TD');
        //data[i]["BODY"] = data[i]["BODY"].replace(/&lt;tr/ig, '<TR');
        data[i]["BODY"] = data[i]["BODY"].replace(/&lt;br\/?>/ig, '<br/>');
        data[i]["BODY"] = data[i]["BODY"].replace(/&lt;(\/?pre)>/ig, '<$1>');
          
        data[i]["TITLE"] = data[i]["TITLE"].replace(/<([a-zA-Z])/g, '&lt;$1');
        
    }
    
}
/*
본문 가공
본문이 제목으로 시작하면 제목 삭제
YNAPHOTO 테그 img 테그로 변환 (img domain 삽입) 등
*/
function $body(title,body)
{
    title = title.replace(/^\s*|\s*$/g, '');    
    body = body.replace(/^\s*|\s*$/g, '');    
    if (body.indexOf(title)==0)
        body = body.replace(title, "");
    body = body.replace(/<YNAPHOTO path/gi, '<img src');
    body = body.replace(/^\s*|\s*$/g, '');    
    body = body.replace(/^<br\/?>(<br\/?>)?/, '');
    body = body.replace(/src=(.)\/contents\//g, "src=$1http://img.yonhapnews.co.kr/");    
    
    return body;
}
/*
리스트용 본문으로 가공
&nbsp; * 4 제거
<br/> 제거
*/
function listBody(body)
{   
    body = body.replace(/&nbsp;&nbsp;&nbsp;(&nbsp;)?/g, '');
    body = $removeImage(body);
    body = body.replace(/<br\/?>\s*<br\/?>/gi, '<br/>');
    body = body.replace(/<br\/?>\s*<br\/?>/gi, '<br/>');
    
    
    //body = body.replace(/<br\/?>\s+/g, '\n');
    return body;
}
/*
본문조회용 본문으로 가공
문단 한줄 더 띄기 
내장사진 가운데 정렬 등
*/
function viewBody(body)
{
    body = body.replace(/<YNAPHOTO path/gi, '<img src');
    body = body.replace(/src=(.)\/contents\//g, "src=$1http://img.yonhapnews.co.kr/");    
    body = body.replace(/<([a-zA-Z])/g, '&lt;$1');
    body = body.replace(/&lt;img /gi, '<img ');
    body = body.replace(/&lt;br\/?>/ig, '<br/>');
    body = body.replace(/&lt;(table|td|tr) /ig, '<$1 ');
    body = body.replace(/&lt;(\/?(center|pre)>)/ig, '<$1');
    
        
    body = body.replace(/    /g, "&nbsp;&nbsp;&nbsp;&nbsp;");
    body = body.replace(/   /g, "&nbsp;&nbsp;&nbsp;");
    body = body.replace(/<br\/?>\n?&nbsp;/ig, '<br/><br/>\n&nbsp;');
    body = body.replace(/。\s*<br\/?>/ig, '。<br/><br/>\n');
    body = body.replace(/<br\/?>\s*<br\/?>\s*<br\/?>/ig, '<br/><br/>');
    
    body = body.replace(/(<img[^>]+>)/gi, '<center>$1</center>');
    
    return body;
}

function printPop(cid)
{
    var win = window.open('../Pop/Pop.aspx?print=1&cid=' + cid,'', "width=710px, menubar=0, scrollbars=1, status=0, location=0");
}
/*
본문 조회
기사번호만 넘기면 팝업조회
2번째 파라미터도 넘기면 
동일한 페이지 조회 및 기사의 해당 페이지 이동
*/
function view(cid,page)
{
    if (page)
    {
        var url = "../News/";
        
        if (/^(AKR[0-9]{17}|OKM[0-9]+K[0-9]+)$/.test(cid))
        {
            site = "ST010100";
            url += "newsList.htm?ctype=C&site=" + site + "&cid=" + cid;
            if (/^O.*/.test(cid))
                url += "&source=H";
        }
        else if (/^A.*/.test(cid))
        {
            site = "ST010900";
            url += "newsList.htm?ctype=FC&site=" + site + "&cid=" + cid;
        }    
        else if (/^P.*/.test(cid) || /^OKM[0-9]+P[0-9]+$/.test(cid))
        {
            site = "ST010600";
            url += "newsList.htm?ctype=P&site=" + site + "&cid=" + cid;
        }
        else if (/^M.*/.test(cid) || /^OKM[0-9]+M[0-9]+$/.test(cid))    
        {
            site = "ST010700"
            url += "newsList.htm?ctype=M&site=" + site + "&cid=" + cid;
        } 
        else
        {
            site = "ST010000";
            url += "newsMain.htm?site=" + site;
        }  
        
        document.location = url;
        return;
    }
    else
    {
         var win = window.open('../Pop/Pop.aspx?cid=' + cid,'', "width=710px, menubar=0, scrollbars=1, status=0, location=0");
         return;
    }
    
    
    
}
/**
run 이 있으면 로딩중
없으면 로딩 완료
*/
function loading(run,e)
{
    if (run)
        document.body.style.cursor = 'wait';
    else
        document.body.style.cursor = 'default';
    if (1==1)
        return;
        
    var div = $('__PROGRESS__');
    if (!div)
    {
        div = document.createElement("DIV");
        div.id = '__PROGRESS__';
        div.style.position = 'absolute';
        div.innerHTML = "<center style='color:blue;'>::::: Loading :::::</center>";
        div.style.backgroundColor = 'yellow';
        div.style.fontColor = 'blue';
        try
        {
            div.style.left = '0px';
            div.style.top = document.body.clientTop;
            div.style.width = '100%';
            //div.style.height = document.body.style.height;//'1000px';    
            div.zIndex = 10000;
            $opacity(div, 50);
            div.style.display = 'none;';        
        
            
        }catch(e)
        {
        
        }
        document.body.insertBefore(div, null);
        //$addEvent(div, 'click', function(){$hide(this);});
    }    
    
    if (run)
        $show(div);
    else
        $hide(div);        
}
function checkLength(src,cnt,dest)
{
    var b = $(src);
    var val = b.value;
    
    var len;
    if (val == '')
        len = 0;
    else
        len = val.length;
        
    if (len > cnt)
    {
        alert(cnt + "자 까지 입력가능합니다. 초과된 내용은 자동으로 삭제됩니다.");
        b.value = val.substring(0,cnt);
        b.focus();
        len = cnt;
    }
    $html(dest, '' + len);
}    

function $search(k)
{
    if (!k)
    {
        alert('키워드를 입력하세요');
        $('searchKeyword').focus();
        return;
    }
    k = k.replace(/^\s*|\s*^/g, '');
    if (k == '')
    {
        alert("키워드를 입력하세요");
        $('searchKeyword').focus();
        return;
    }
    if ((k.charCodeAt(0) < 127 && k.length == 1) || /^[<>\/'\";:\[\]\{\}.,~`!@#$%^&*\(\)\-_+=\|\\?]+$/.test(k))
    {
        alert("사용할 수 없는 키워드입니다.");
        $('searchKeyword').focus();
        return;
    } 
    
    $('searchKeyword').value = '';    
    var f = $('searchForm');
    
    if (f)
    {
        $('keyword1').value = k;
        f.page.value = '1';
        search('APM', '*', '전체', 'Y');
    }
    else
    {    
        //document.location="../Search/search.htm?site=ST080000&ctype=APM&keyword=" + keyword + "#page=1";    
        
        document.location="../Search/search.htm?site=ST080000#page=1&ctype=APM&keyword=" + k;            
    }
}

function addFavor()
{
    if (document.all)
        window.external.AddFavorite("http://www.koreancenter.or.kr", "한민족포탈");
    else
        window.sidebar.addPanel("한민족포탈", "http://www.koreancenter.or.kr", "");

}
function toLogin()
{
    if (document.URL.indexOf("login.htm") > 0)
        return;
    
    loginPop();
    /*
    if (1 == 1)
        return;
        
    var url = "../Login/login.htm?returnURL=";
    if (document.URL.indexOf("returnURL") < 0)
        url += escape(document.URL);       
    document.location = url;
    */
}


function toLogout()
{
    $get("../Login/logout.aspx?r=" + new Date(), [], logoutResult, true);
}
function logoutResult(xhr)
{   
    loadHeader();
    try
    {
        if (parsePage)
            parsePage();
    }catch(e){}    
}
function write2Admin()
{
    popWin = window.open("../World/boardList.htm?write=1", "관리자에게");    
    //document.location = "../World/boardList.htm?write=1";
    
}
function writeMe()
{   
    popWin = window.open("../world/article_record.aspx", "내글쓰기");
    //document.location = " http://www.koreancenter.or.kr/YNA/KoreanPortal/world/article_record.aspx";
}

/*
function thisMovie(movieName) 
{
    
		if (navigator.appName.indexOf("Microsoft") != -1) {
			return window[movieName]
		}
		else {
			return document[movieName]
		}
}
*/




function setDepthCode(site)
{
        
    depth1Code = "";
    depth2Code = "";
    depth3Code = "";
    if (site && site.length == 8)
    {
        depth1Code = site.substring(0, 4) + "0000";
        depth2Code = site.substring(0, 6) + "00";
        depth3Code = site;
        if (/.*[0]{4}$/.test(site))
        {
            depth2Code = "";
            depth3Code = "";
        }
        else if (/.*[0]{2}$/.test(site))
        {
            depth3Code = "";
        }
        
        /*
        if (/ST010[0-5].* /.test(site) || /ST01080[01]/.test(site))
            ctype = 'A';
        else if (/ST0106.* /.test(site) || /ST010802/.test(site))
            ctype = 'P';
        else if (/ST0107.* /.test(site) || /ST010803/.test(site))
            ctype = 'M';
        else if (/ST0109.* /.test(site))
            cytpe = 'F';
        */    
        currentSite = site;
    }
    else
    {
        site = "";
    }
    	    
    if (!site || site.length < 8)
        return;
    
    var lnbF = $('lnbFlash');
    
    if (lnbF)
    {
        if (lnbF.locationSetting)        
            lnbF.locationSetting(depth1Code, depth2Code, depth3Code);    
        else
        {
            var em = lnbF.getElementsByTagName("EMBED");
            if (em && em[0] && em[0].locationSetting)
            {
                em[0].locationSetting(depth1Code, depth2Code, depth3Code);    
            }
        }
    }
    
    var subF = $('subFlash');
    
    if (subF)
    {
        if (subF.locationSetting)
            subF.locationSetting(depth1Code, depth2Code, depth3Code);
        else
        {
            var em = subF.getElementsByTagName("EMBED");
            if (em && em[0] && em[0].locationSetting)
            {
                em[0].locationSetting(depth1Code, depth2Code, depth3Code);    
            }
        }
    }
     
}
function loadHeader()
{
    var cook = $cookie()
    var id = cook["USERID"];
    var cls = cook["CLS"];
    var seqno = cook["ADMSEQNO"];
    
    var h = (id && cls) ? COMMON['header2'] : COMMON['header'];
    var txt = $template(h);    
    if (cls == 'C')
        txt = txt.replace(/__NAME__/, decodeURIComponent($cookie("COMPANYNM")));
    else
        txt = txt.replace(/__NAME__/, decodeURIComponent($cookie("USERNM")) + "님");
    
    if (/[SME]/.test(cls))
    {
        txt = txt.replace(/__ADMIN__/, "<li class='info_line' id='toAdmin'><a target='popWin' href='../Admin/adminManager.htm'>관리자메뉴</a><li>");
        txt = txt.replace(/__WRITE__/, "");
        txt = txt.replace(/<.*__EVENT__.*>/, "");
        txt = txt.replace(/__EVENT__/, "");
        txt = txt.replace(/__INFO__/, "");
    }    
    else if (/[CU]/.test(cls))
    {
        txt = txt.replace(/__ADMIN__/, "<li class='info_line' id='toAdmin'><a href='javascript:write2Admin();'>관리자에게</a><li>");        
        txt = txt.replace(/__WRITE__/, "<li class='info_line' id='writeMenu'><a href='javascript:writeMe();'>뉴스등록</a><li>");
        txt = txt.replace(/__EVENT__/, "<li class='info_line' id='eventRegist'><a href='../World_Event/event_photo_record.aspx' target='_blank'>이벤트등록</a><li>");
        txt = txt.replace(/__INFO__/, "<li class='info_line' id='infoEdit'><a href='../member/edit_form1.aspx'>내정보수정</a><li>");
            
    }
    else if (/[P]/.test(cls))
    {
        var url = "../Community/qna.aspx?type=count&seqno=" + seqno;
        $clearFile(url);
        var json = $json($txt(url));
        txt = txt.replace(/__ADMIN__/, "");
        txt = txt.replace(/__WRITE__/, "<li class='info_line' id='writeMenu'><a href='../Community/qna.htm?pannel=" + id + "'>내글쓰기" + json['total'] + "</a><li>");
        txt = txt.replace(/<.*__EVENT__.*>/, "");
        txt = txt.replace(/__EVENT__/, "");
        txt = txt.replace(/__INFO__/, "<li class='info_line' id='infoEdit'><a href='../member/edit_form2.aspx'>내정보수정</a><li>");
    }
    else if (/[B]/.test(cls))
    {
        txt = txt.replace(/__ADMIN__/, "");
        txt = txt.replace(/__WRITE__/, "<li class='info_line' id='writeMenu'><a href='../Community/manager_list.htm?site=ST020000&admSeqNo=" + seqno + "'>내글쓰기</a><li>");
        txt = txt.replace(/<.*__EVENT__.*>/, "");
        txt = txt.replace(/__EVENT__/, "");
        txt = txt.replace(/__INFO__/, "<li class='info_line' id='infoEdit'><a href='../member/edit_form3.aspx'>내정보수정</a><li>");
    }
    else
    {
        txt = txt.replace(/__ADMIN__/, "");
        txt = txt.replace(/__WRITE__/, "");
        txt = txt.replace(/<.*__EVENT__.*>/, "");
        txt = txt.replace(/__EVENT__/, "");
        txt = txt.replace(/__INFO__/, "");
    }
    
    $html('header', txt);
    $show('header');
    $setTitleImage(site);
    var ft = $template(COMMON['footer']);
    $html('footer', ft);
    
}
function initPage()
{   
    setTimeout(loadHeader,300);
    
    $import('../js/pcid.js');
    $import('../js/twit.js');
    $import('../js/facebook.js');
}

function $member(random)
{
    if (random)
    {
        var url = "../Main/main.aspx?type=member&json=1";
        $clearFile(url);        
        var txt = $txt(url);
        var js = $json(txt);
        var home = js["HOME"];
        
        var json = {};
        
        json['HOME'] = home;
        json['COMPANYNM'] = js["NAME"];
        json['INTRO'] = js["INTRO"];
        return json;
    }
    else
    {
        var url = "../Code/code.aspx?json=1&codetype=Member&status=A&cls=[CU]";
        var json = $json($txt(url));
        return json;
    
    }    
}
function setMember()
{
    var mem = $member(true);
    var home = mem['HOME'];
    home = home.replace(/http:\/\//i, '');    
    if ($('memberHref'))
        $('memberHref').innerHTML = "<a href='http://" + home + "' target='_blank'>" + mem['COMPANYNM'] + "</a>";
    if ($('memberHrefMain'))
        $('memberHrefMain').innerHTML = "<a href='http://" + home + "' target='_blank'>" + mem['COMPANYNM'] + "</a> <span class='txt_date'>" + home + "</span>";
    if ($('memberHome'))
        $('memberHome').innerHTML = home.replace(/\./g, '. ');
    if ($('memberIntro'))
        $('memberIntro').innerHTML = mem["INTRO"];
}
function getParameter(key)
{
    var h = $hash();
    var q = $query();
    if (h && h[key] && h[key].length > 0)
        return h[key];
    if (q && q[key])
        return q[key];
    return null;
}

function hideLoginPop()
{
    //document.body.removeChild($('loginLayer'));
    $hide('loginLayer');
}
function loginPop(suc,fail)
{
    LoginFunction = {};
    if ($cookie('USERID') && $cookie('CLS'))
    {
        alert('이미 로긴하셨습니다');
        return;
    }
    LoginFunction['success'] = suc;
    LoginFunction['fail'] = fail;
    
    var div = $('loginLayer');
    if (!div)
    {
        div = document.createElement("DIV");
        div.id = 'loginLayer';
        div.zIndex = 15000;
        div.backgroundImage = "../images/common/login_bg.png";
        div.style.position = 'absolute';
        div.innerHTML = $template("../Common/loginBody.htm");
        div.style.display = 'none';
        document.body.insertBefore(div, null);
        
    }
    div.zIndex = 15000;
    var x = 0;
    var y = 150;
    var t = Math.floor(Math.random()*100);
    if (t%2 == 1)
        x = -1000;
    t = Math.floor(Math.random()*100);
    $('txtID').value = '';
    $('txtPassword').value = '';
    if ($("loginForm"))
        $("loginForm").reset();
    
    //$moveTo(div, 300, -500);
    $moveTo(div, x, y);
    $opacity(div, 100);
    $show(div);
    $('txtID').focus();
    if (!document.all)
        $fade(div, 0, 100, 10, 2);
    $moveTo(div, 300, 150, 4, 5);    
    
}
function $submitLogin()
{
    var op = $('loginForm');
    if (op)
    {
        if ($('txtID').value == "" )
        {
            alert("아이디를 입력하십시오.");
            if ($('txtID'))
                $('txtID').focus();
            return;
            
        }else if($('txtPassword').value == "")
        {
            alert("비밀번호를 입력해주십시오.");
            if ($('txtPassword'))
                $('txtPassword').focus();
            return;
        }
        var f = $('loginForm');
        if (f)
        {
            f.txtID.value = $('txtID').value;
            f.txtPassword.value = $('txtPassword').value;            
            $submit('loginForm', $loginResult,true);
        }
    }
}
// 로긴 후 실행할 함수 등록
// suc 로긴성공했을때 실행할 함수
// fail 로긴 실패 했을때 실행할 함수
function setLoginFunction(suc,fail)
{
    LoginFunction['success'] = suc;
    LoginFunction['fail'] = fail;
}
// 로그아웃 했을때 실행할 함수 등록
function setLogoutFunction(func)
{
    LoginFunction['logout'] = func;
}
// 로그아웃 함수를 수행
// 실행 후에는 등록된 함수는 소멸된다.
function doLogoutFunction()
{
    if (typeof LoginFunction['logout'] == 'function')
        LoginFuction['logout']();
    else
    {
        eval(LoginFunction['logout'] + '()');
    }
    LoginFunction['logout'] = null;
}
// 로그인 성공시 함수 수행
// 실행 후에는 소멸됨.
function doLoginSuccess()
{
    if (typeof LoginFunction['success'] == 'function')
    {
        LoginFunction['success']();
    }
    else
    {
        eval(LoginFunction['success'] + '()');
    }
    LoginFunction['success'] = null;
    LoginFunction['fail'] = null;
}
// 로그인 실패시 함수 수행
function doLoginFail()
{
    if (LoginFunction && LoginFunction['fail'])
    {
        if (typeof LoginFunction['fail'] == 'function')
            LoginFunction['fail']();
        else
            eval(LoginFunction['fail'] + '()');
    }    
    LoginFunction['fail'] = null;  
}
// 로긴시 콜백 함수
function $loginResult(xhr)
{
    var txt = xhr.responseText;    
    //alert(txt);
    var json = $json(txt);
    
    if(json["result"] == "-2")
    {
        alert("회원정보가 존재하지 않습니다.");
        doLoginFail();  
    }else if(json["result"] == "-1")
    {
        alert("비밀번호가 일치하지 않습니다.");
        doLoginFail();
    }else if(json["result"] == "0")
    {
        //$cookie("USERID", json["userid"], 1);
        //$cookie("CLS", json["cls"], 1);
        //$cookie("ADMSEQNO", json["admseqno"], 1);
        //$cookie("USERNM", json["usernm"], 1);
        //$cookie("STATUS", json["status"], 1);
        //$cookie("COMPANYNM", json["companynm"], 1);
        
        hideLoginPop();    
        loadHeader();
        
        if (LoginFunction && LoginFunction['success'])
        {
            doLoginSuccess();
        }
        else
        {
            try
            {
                if (parsePage)
                {   
                    parsePage();
                }                
            }catch(e)
            {}       
        }
        
    }else
    {
        alert("인증에 실패하였습니다.\n잠시후 다시 시도해주세요");
        doLoginFail();  
    }
    $('loginForm').reset();
    
}



function getCopyright(cid)
{
    var cr; 
    if (cid.charAt(0) == 'O')
        cr = COPYRIGHT['H'];
    else if (/^(AKR|MYH|PYH).*/.test(cid))
        cr = COPYRIGHT['A'];
    else
        cr = COPYRIGHT['F'];  
    return cr;
}
/*
저작권 문구 설정
*/
function setCopyright(cid)
{   
    var cr = getCopyright(cid);
    $html('article_copy', cr);
    return cr;
}

/*
저작권 규약 팝업
*/
function copyright()
{
    var win = window.open("../Common/copyright.html", '', "width=700px, height=685px, menubar=0, status=0, location=0");
}


/*타이틀 이미지 변경
*/
function $setTitleImage(sitecd)
{
    if (!sitecd)
    {
        sitecd = getParameter('site');
    }
    if (sitecd && $('titleImage'))
    {
        $('titleImage').src = "../images/title/tlt_" + sitecd + ".gif";
    }
}

 
window.onresize = checkLayout;
window.onload = checkLayout;
window.onfocus = checkLayout;


var depth1Code = "";
var depth2Code = "";
var depth3Code = "";
var site = getParameter("site");
var ctype = 'A';
var currentSite;
initPage();
setDepthCode(site);    

    
