﻿/////////////////////////////////////////////////////////////////////////
//  Ajax Div 라이브러리 v0.5 (Based on Ajax Library v0.2)
//  by wiluby(Eugene Song, wiluby@gmail.com), 2006~2008
/////////////////////////////////////////////////////////////////////////

var gAgent = new Agent();

/*
Ajax 사용하기
    
args)
url : 대상 URL
options : 옵션

options)
tag             : 여러 Ajax를 이용하는데 필요한 Tag 구분 값(임의 정의), onXXXX 이벤트를 공동으로 사용할 때 Ajax의 구분을 위해서 필요
method          : "get", "post" (기본값 : get)
update          : update될 div 혹은 span의 element id
evalScript      : script tag의 실행 여부(true/false) 기본 : false
content         : 보낼 데이터(name1=value&name2=value)
onComplete      : 요청 완료 콜백 지정(성공/실패 구분 안함)
onSuccess       : 요청 성공 콜백 지정(HttpStatus가 200일 때 호출)
onError         : 요청 실패 콜백 지정(HttpStatus가 200이 아닐 때 호출)
onStart         : 요청 시작 바로 전에 호출
onFinish        : 모든 처리가 끝나고 dispose 바로 전에 호출

*참고* 자동으로 객체가 dispose 되니. 결과 후 필요한 처리는 onXXXXXX() 콜백으로 미리 처리할 것
sample)
    
<script language="javascript" src="/js/Ajax.js"></script>
<script language="javascript">
<!--

new Ajax("http://sample.surae.com/SuraeIN/GetData.aspx?opt=123", {tag:'ajax1', method:'get', update:'divResult', content:'name=babo&value=1234', onComplete:function(ajax) { }, onSuccess:function(ajax) { }, onError:function(ajax) { } });
            
function myFunction(ajax)
{
alert(ajax.getStatus());
alert(ajax.getStatusText());
alert(ajax.getResponseText());
}
//-->
</script>
*/

function $exec(text) { if (!text || text.length < 1) return text; if (window.execScript) { window.execScript(text); } else { var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); if (script.innerText) script.innerText = text; else script.text = text; document.body.appendChild(script); document.body.removeChild(script); } return text; }

function Ajax(url, options) {
    var obj = new Object();

    obj.URL = window.location.href;
    obj.tag = options["tag"] != undefined ? options["tag"] : null;
    obj.Request = null;
    obj.update = options["update"] != undefined ? options["update"] : null;
    obj.evalScript = options["evalScript"] != undefined ? options["evalScript"] : false;
    obj.method = options["method"] != undefined ? options["method"] : "get";

    obj.onComplete = options["onComplete"];
    obj.onSuccess = options["onSuccess"];
    obj.onError = options["onError"];

    obj.onStart = options["onStart"];
    obj.onFinish = options["onFinish"];

    obj.resText = '';
    obj.resScript = '';

    obj.cancel = function() { if (obj.Request != null) obj.Request.abort(); };
    obj.dispose = function() { if (obj.Request == null) return; obj.cancel(); delete obj.Request['onreadystatechange']; delete obj.Request; obj.Request = null; };
    obj.getStatus = function() { if (obj == null || obj.Request == null) return null; return obj.Request.status; };
    obj.getStatusText = function() { if (obj == null || obj.Request == null) return null; return obj.Request.statusText; };
    obj.getResponseText = function() { if (obj == null || obj.Request == null) return null; return obj.evalScript ? obj.resText : obj.Request.responseText; };
    obj.getResponseScript = function() { return obj.resScript; };
    obj.getResponseXML = function() { if (obj == null || obj.Request == null) return null; return obj.Request.responseXML; };

    obj.innerComplete = function() {
        if (obj == null || obj.Request == null) { return; }
        if (obj.Request.readyState == 4 || obj.Request.readyState == 'complete') {
            obj.evalScript = obj.evalScript != null && obj.evalScript != undefined && obj.evalScript; obj.resText = ''; obj.resScript = '';
            if (obj.evalScript) { obj.resText = obj.Request.responseText.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function() { obj.resScript += arguments[1] + '\n'; return ''; }); }
            if (obj.update != null && obj.update != undefined) { document.getElementById(obj.update).innerHTML = obj.getResponseText(); }
            if (obj.evalScript) { $exec(obj.resScript); }
            if (typeof (obj.onComplete) == "function") { obj.onComplete(obj); }
            if (obj.Request.status == 200 && typeof (obj.onSuccess) == "function") { obj.onSuccess(obj); }
            else if (obj.Request.status != 200 && typeof (obj.onError) == "function") { obj.onError(obj); }
            if (typeof (obj.onFinish) == "function") { obj.onFinish(obj); }
            obj.dispose(); obj = null;
        }
    };

    try { obj.Request = new XMLHttpRequest(); }
    catch (trymicrosoft) {
        try { obj.Request = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch (othermicrosoft) {
            try { obj.Request = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch (failed) { obj.Request = false; }
        }
    }

    if (!obj.Request) { return null; }

    obj.Request.open(obj.method, url, true);
    if (obj.method == "post" || obj.method == "POST") {
        // POST 방식에서는 content-type을 꼭!!!
        obj.Request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    }

    if (gAgent.isOpera || gAgent.isSafari || gAgent.isGecko) { obj.Request.onload = obj.innerComplete; } else { obj.Request.onreadystatechange = obj.innerComplete; }
    if (typeof (obj.onStart) == "function") { obj.onStart(obj); }
    obj.Request.send(options["content"] != undefined ? options["content"] : null);

    return obj;
}

/* common */

function getAbsoluteTop(oNode) {
    var oCurrentNode = oNode; var iTop = 0;
    while (oCurrentNode != null && oCurrentNode.tagName != "BODY") {
        iTop += oCurrentNode.offsetTop; // - oCurrentNode.scrollTop;
        oCurrentNode = oCurrentNode.offsetParent;
    } return iTop;
}

function getAbsoluteLeft(oNode) { var oCurrentNode = oNode; var iLeft = 0; iLeft += oCurrentNode.offsetWidth; while (oCurrentNode != null && oCurrentNode.tagName != "BODY") { iLeft += oCurrentNode.offsetLeft; oCurrentNode = oCurrentNode.offsetParent; } return iLeft; }

// 특정 객체에 이벤트를 추가 obj : 대상 객체 eventtype : 이벤트 타입 (click, load, etc...) handler : 처리 루틴?  리턴값 : false 이면 대상 객체에 직접 맵핑하므로 중복 수행할 때 문제될 수 있으므로 false 리턴
function addEvent(obj, eventtype, handler) {
    if (obj.attachEvent) { obj.attachEvent('on' + eventtype, handler); return true; }
    else if (obj.addEventListener) { obj.addEventListener(eventtype, handler, false); return true; } else { obj['on' + eventtype] = handler; return false; }
}
function removeEvent(obj, eventtype, handler) { if (obj.removeEventListener) { obj.removeEventListener(eventtype, handler, false); return true; } else if (obj.detachEvent) { obj.detachEvent("on" + eventtype, handler); return false; } else { return false; } }

// 브라우져 확인 객체
function Agent() { this.isIE = navigator.userAgent.match(/MSIE/); this.isGecko = navigator.userAgent.match(/Gecko/); this.isSafari = navigator.userAgent.match(/AppleWebKit/); this.isChrome = navigator.userAgent.match(/Chrome/); this.isOpera = window.opera; if (!document.all || this.isGecko || this.isSafari || this.isOpera || this.isChrome) { this.isIE = false; } this.isIE6 = this.isIE && navigator.userAgent.match(/MSIE 6\./); this.isIE7 = this.isIE && navigator.userAgent.match(/MSIE 7\./); this.isIE8 = this.isIE && navigator.userAgent.match(/MSIE 8\./); return this; }

// 특정 엘리먼트 위치 고정
function SetFixPosition(id, minheight) {
    var obj = $(id);
    if (id == null)
        return;

    window.onscroll = function() {
        var posy = getScrollXY()[1];

        if (posy <= minheight) {
            obj.style.position = 'absolute';
            obj.style.top = minheight + 'px';
        }
        else {
            obj.style.position = 'absolute';
            obj.style.top = posy + 'px';
        }
    }
}

// http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if (typeof (window.pageYOffset) == 'number') {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [scrOfX, scrOfY];
}

// Function Name : findPos
// Parameter : obj - owner of event occurence object
// Description : Get offsetLeft, offsetTop
function findPos(obj) {
    var curleft = curtop = 0;

    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    else if (obj.x || obj.y)			// for safari of old version
    {
        if (obj.x) curleft += obj.x;
        if (obj.y) curtop += obj.y;
    }
    return [curleft, curtop];
}

function showFlash(_swfURL_, _flashID_, _width_, _height_, _wmode_, _flashVars_, _bgColor_, _fullscreen_) {
    _wmode_ = (_wmode_ == undefined) ? "transparent" : _wmode_;
    _bgColor_ = (_bgColor_ == undefined) ? "#000000" : _bgColor_;
    _fullscreen_ = (_fullscreen_ == undefined) ? "false" : _fullscreen_;
    if (navigator.userAgent.match(/MSIE/) && navigator.userAgent.match(/win/i) && !window.opera) {
        _object_ = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="' + _width_ + '" height="' + _height_ + '" id="' + _flashID_ + '" align="middle">';
        _object_ += '<param name="allowScriptAccess" value="always" />';
        _object_ += '<param name="quality" value="high" />';
        _object_ += '<param name="movie" value="' + _swfURL_ + '" />';
        _object_ += '<param name="wmode" value="' + _wmode_ + '" />';
        _object_ += '<param name="allowFullScreen" value="' + _fullscreen_ + '">';
        _object_ += '<param name="bgcolor" value="' + _bgColor_ + '" />';
        _object_ += '<param name="FlashVars" value="' + _flashVars_ + '">';
        _object_ += '</object>';
    } else {
        _object_ = '<embed src="' + _swfURL_ + '" quality="high" wmode="' + _wmode_ + '" allowFullScreen="' + _fullscreen_ + '" FlashVars="' + _flashVars_ + '" bgcolor="' + _bgColor_ + '" width="' + _width_ + '" height="' + _height_ + '" name="' + _flashID_ + '" id="' + _flashID_ + '" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
    }
    document.write(_object_);
}

// flash external 통신이 있을 경우 unload 시 호출해줄 것(이유 memory leak 처리)
function CleanupExternalFlash() {
    obj = document.getElementsByTagName('OBJECT');
    for (i = 0; i < obj.length; i++) {
        var theObj = eval(obj[i]);
        theObj.style.display = "none";
        for (var prop in theObj) {
            if (typeof (theObj[prop]) == "function") {
                theObj[prop] = null
            }
        }
    }
}
//addEvent(window, 'unload', CleanupExternalFlash);

function GetSwf(swfid) {
    var browser = navigator.appName.match(/Microsoft/i);
    if (browser == 0) {
        return document.all[movieName];
    } else if (browser == -1) {
        return document[movieName];
    }
}

// prototype $ function
// getelementbyid
function $() {
    var ret = [];
    for (var n = 0; n < arguments.length; n++) {
        if (typeof arguments[n] == 'string') {
            ret[ret.length] = document.getElementById(arguments[n]);
        } else {
            ret[ret.length] = arguments[n];
        }
    }
    return ret[1] ? ret : ret[0];
}
// getelementbyname
function $E(name) { return document.getElementsByName(name); }
// get cookie
function $C(id) { var c = document.cookie.split(/\s*;\s*/); var r = new RegExp('^(\\s*' + id + '\\s*=)'); for (var i = 0; i < c.length; i++) { if (r.test(c[i])) { return decodeURIComponent(c[i].substr(RegExp.$1.length)) } } return ''; }
function $SC(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());
    if (expires) { expires = expires * 1000 * 60 * 60 * 24; }
    var expires_date = new Date(today.getTime() + (expires));
    document.cookie = name + "=" + escape(value) +
        ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
        ((path) ? ";path=" + path : "") +
        ((domain) ? ";domain=" + domain : "") +
        ((secure) ? ";secure" : "");
}
function $Q(id) { if (window.location.search.length < 2) return ''; var args = window.location.search.substring(1).split("&"); for (var i = (args.length - 1); i >= 0; i--) { var namevalue = args[i].split("="); if (namevalue[0] == id) return namevalue[1]; } return ''; }

// 지정된 radio 그룹에서 특정 값을 가진 radio를 선택
function $SETRDO(name, value) {
    var objs = $E(name);
    var objlen = objs.length;

    if (objlen == undefined) {
        objs.checked = (objs.value == value);
        return;
    }
    for (var i = 0; i < objlen; i++) {
        //objs[i].checked = false;
        if (objs[i].value == value) {
            objs[i].checked = true; return;
        }
        else
            objs[i].checked = false;
    }
}
// 지정된 radio 그룹에서 선택된 값을 리턴
function $GETRDO(name) {
    var objs = $E(name);
    if (objs == undefined) return '';
    for (var n = 0; n < objs.length; n++) {
        if (objs[n].checked) {
            return objs[n].value;
        }
    }

    return '';
}
// 해당 checkbox를 체크
function $SETCHK(id, chk) {
    $(id).checked = chk ? chk : true;
}
// 해당 checkbox의 체크 여부
function $GETCHK(id) {
    try {
        return $(id).checked;
    }
    catch (e) {
    }
    return false;
}

// get value (if v is undefined or null, return dv)
function $V(v, dv) { if (v != undefined && v != null) return v; return dv; }

function $TDISPLAY(id) { try { var obj = $(id); if (obj.style.display == 'block') obj.style.display = 'none'; else obj.style.display = 'block'; } catch (e) { } }

function $SHOWB(id) { try { $(id).style.display = 'block'; } catch (e) { } }
function $SHOWI(id) { try { $(id).style.display = 'inline'; } catch (e) { } }
function $HIDEB(id) { try { $(id).style.display = 'none'; } catch (e) { } }
function $SHOW(id) { try { $(id).style.visibility = 'visible'; } catch (e) { } }
function $HIDE(id) { try { $(id).style.visibility = 'hidden'; } catch (e) { } }

function $html(id, htmltext) {
    try {
        $(id).innerHTML = htmltext;
    }
    catch (e) {
    }
}

function $focus(id) {
    try { $(id).focus(); } catch (e) { }
}

function $blur(id) {
    try { $(id).blur(); } catch (e) { }
}

//천단위,삽입
function MaekCommaNumber(val) {
    return getMoneyString(val);
}

/// 천단위 , 으로 리턴
function getMoneyString(val) {
    val += '';
    val = val.replace(/[^0-9]/g, '');
    var reg = /(^[+-]?\d+)(\d{3})/;
    while (reg.test(val)) val = val.replace(reg, '$1' + ',' + '$2');
    return val;
}

// 천단위 , 값을 숫자로 리턴
function getMoneyInt(val) {
    if (typeof val == 'undefined' || val == null) return 0;
    val += '';
    val = val.replace(/[^0-9]/g, '');
    var reg = val.replace(/,/g, '');
    return isNaN(reg) ? 0 : parseInt(reg);
}

function CutString(str, len, endmark) {
    var l = 0;
    for (var i = 0; i < str.length; i++) {
        l += (str.charCodeAt(i) > 128) ? 2 : 1;
        if (l > len) return str.substring(0, i) + (endmark!=null && endmark.length>0 ? endmark : '');
    }
    return str;
}

function fixstr(val, max, ext) {
    if (val == undefined || val == null || val == '') return '';
    return max != undefined && max < val.length ? val.substr(0, max) + (ext != undefined ? ext : '') : val;
}

function getplaintext(val) {
    return val.replace(/</g, "&gt;").replace(/>/g, "&lt;");
}

function isImageFile(filename) {
    return (/(.jpg|.jpeg|.png|.gif)$/gi).test(filename);
}


function NR2BR(val) {
    return val.replace(/\n/g, '<br/>');
}

function setPressKeyEvent(objid, key, fn) {
    var tobj = $(objid);
    if (tobj == undefined || tobj == null) return;
    addEvent(tobj, 'keypress', function() { if (event.keyCode == key) { return fn(objid); } });
}

function getNodeValue(node) { try { return node.childNodes[0].nodeValue; } catch (e) { } return ''; }
function getNodeAttrValue(node, idx) { try { return node.attributes[idx].nodeValue; } catch (e) { } return ''; }

// 엘리먼트 종류에 따라서 자동 값 넣어주기
function addQueryValue(id) {
    var obj = $(id);
    if (obj == undefined) return '';
    switch (obj.type) {
        case 'text':
        case 'password':
        case 'hidden':
        case 'textarea': { return encodeURIComponent(obj.value); } break;
        case 'checkbox':
        case 'radio': { return encodeURIComponent(obj.checked ? 'Y' : 'N'); } break;
        default: { return getSelectBoxValue(id); } break;
    }
}

// 주어진 엘리먼트 객체를 query string으로 조합
function addQueryValues(idlist) {
    if (idlist == undefined || idlist.length < 1) return;
    var url = '';
    for (var key in idlist) { if (idlist[key] != undefined) url += "&" + key + "=" + addQueryValue(idlist[key]); }
}
// 엘리먼트 종류에 따라서 자동 값 초기화
function clearQueryValue(id) {
    var obj = $(id);
    if (obj == undefined) return;
    switch (obj.type) {
        case 'text':
        case 'password':
        case 'hidden':
        case 'textarea': { obj.value = ''; } break;
        case 'checkbox':
        case 'radio': { obj.checked = false; } break;
        default: { resetSelectBox(id); } break;
    }
}

// 엘리먼트 종류에 따라서 값 가져오기
function $get(id, defvalue) {
    var obj = $(id);
    if (defvalue == undefined) defvalue = '';
    if (obj == undefined) return defvalue;
    switch (obj.type) {
        case 'text':
        case 'password':
        case 'hidden':
        case 'textarea': { return obj.value; } break;
        case 'checkbox':
        case 'radio': { return obj.checked; } break;
        default: { return getSelectBoxValue(id); } break;
    }
}

// 엘리먼트 종류에 따라서 값 넣어주기
function $set(id, value, textvalue) {
    var obj = $(id);
    if (obj == undefined) return;
    switch (obj.type) {
        case 'text':
        case 'password':
        case 'hidden':
        case 'textarea': { obj.value = value; } break;
        case 'checkbox':
        case 'radio': { obj.checked = value; } break;
        default: { return setSelectBoxValue(id, value, textvalue); } break;
    }
}


// 주어진 엘리먼트 객채를 모두 초기화
function clearQueryValues(idlist) {
    if (idlist == undefined || idlist.length < 1) return;
    for (var key in idlist) { if (idlist[key] != undefined) clearQueryValue(idlist[key]); }
}

function clearQueryValueArray(idlist) {
    if (idlist == undefined || idlist.length < 1) return;
    for (var n = 0; n < idlist.length; n++) { clearQueryValue(idlist[n]); }
}

// 문자열 조작(문자열 전체 문자열, 대소문자 구분)
String.prototype.replaceAll = function(oldValue, newValue) {
    return this.replace(new RegExp(oldValue, 'g'), newValue);
};
// 문자열 트림
String.prototype.trim = function() {
    return this.replace(/(^ *)|( *$)/g, '');
};
// 문자열 좌측트림
String.prototype.ltrim = function() {
    return this.replace(/(^ *)/g, '');
};
// 문자열 우측트림
String.prototype.rtrim = function() {
    return this.replace(/( *$)/g, '');
};
// 문자열이 숫자인지
String.prototype.isNumber = function() {
    return !isNaN(this);
}
// 숫자 얻기(숫자가 아니거나 빈문자열이면 0)
String.prototype.getNumber = function() {
    if (this.isEmpty() || !this.isNumber()) {
        return 0;
    }
    return parseInt(this, 10);
}
// 빈문자열인지 여부
String.prototype.isEmpty = function() {
    return this.length < 1 ? true : false;
}

// 바탕화면 클릭시 사라지는 엘리먼트 관리 및 처리
var aElements = {};
// 사라지는 처리 시에 부모가 아니지만 연계되어 있는 엘리먼트의 경우 hideid에 넣음
function addAutoHide(id, hideid) {
    if (aElements[id] == undefined) aElements[id] = hideid != undefined ? hideid : '$$';
}
function removeAutoHide(id) {
    if (aElements[id] != undefined) delete aElements[id];
}
function hideAutoHide() {
    for (var key in aElements) {
        var obj = $(key);
        if (event != undefined && event.srcElement != undefined && obj != undefined) {
            if (IsChildNode(event.srcElement, obj)) return;
            if (aElements[key] != '$$' && IsChildNode(event.srcElement, $(aElements[key]))) return;
        }
        if (aElements[key] != '$$') { $HIDEB(aElements[key]); }
        else if (obj != undefined) obj.style.display = 'none';
    }
}
addEvent(document, 'click', hideAutoHide);

// 하위 노드인지 탐색(event node, 하위인지 판단하는 부모 node)
function IsChildNode(oNode, oChild) {
    var oCurrentNode = oNode;
    while (oCurrentNode != null && oCurrentNode.tagName != "BODY") {
        if (oCurrentNode == oChild) return true;
        oCurrentNode = oCurrentNode.offsetParent;
    }
    return false;
}

// 레이어를 추가
// autohide = true:auto hide(default), false: permanent
function addLayer(id, cssclass, display, autohide, x, y, ab, alone, w, h) {
    var divLayer = $(id);

    if (divLayer == undefined) {
        divLayer = document.createElement("DIV");
        divLayer.id = id;
        divLayer.name = id;
        divLayer.tag = alone ? 1 : 0;
        if (cssclass != undefined) divLayer.className = cssclass;
        divLayer.style.display = display != undefined ? display : 'none';
        if (ab) divLayer.style.position = 'absolute';
        document.body.appendChild(divLayer);
        if (autohide != undefined && autohide) addAutoHide(id);
    }
    if (x) divLayer.style.left = (x - 15 > 0 ? x - 15 : 0) + 'px';
    if (y) divLayer.style.top = (y - 15 > 0 ? y - 15 : 0) + 'px';
    if (w) divLayer.style.width = w + 'px';
    if (h) divLayer.style.height = h + 'px';

    return divLayer;
}

// 레이어 제거
function removeLayer(id) {
    var obj = $(id);
    if (obj != undefined)
        obj.parentNode.removeChild(obj);

    obj = null;

    return false;
}
// 레이어 보이기
function showLayer(id) {
    $SHOWB(id);
    var obj = $(id);
    /*    if(obj!=undefined){
    var x=parseInt(obj.style.left);
    var y=parseInt(obj.style.top);
    var w=parseInt(obj.offsetWidth);
    var h=parseInt(obj.offsetHeight);
    var bw=parseInt(document.body.clientWidth);
    var bh=parseInt(document.body.clientHeight);
    if(x+w>bw) obj.style.left=(bw-w)+'px';
    if(y+h>bh) obj.style.top=(bh-h)+'px';
    } /**/
    try { $(id).focus(); } catch (e) { }
}
// 레이어 숨기기
function hideLayer(id) {
    $HIDEB(id);
}

function moveLayerToEvent(id, alignx, aligny) {
    var pos = getCurrentXY();

    var obj = $(id);
    if (id == undefined) return;
    obj.style.left = (pos[0] + (alignx != undefined ? alignx : 0)) + 'px';
    obj.style.top = (pos[1] + (aligny != undefined ? aligny : 0)) + 'px';
    obj.style.display = 'block';

    $HIDE(id);
    obj.style.display = 'block';
    var x = (pos[0] + (alignx != undefined ? alignx : 0));
    var y = (pos[1] + (aligny != undefined ? aligny : 0));
    x = x + obj.offsetWidth > document.body.offsetWidth ? document.body.offsetWidth - obj.offsetWidth : x;
    y = y + obj.offsetHeight > document.body.offsetHeight ? document.body.offsetHeight - obj.offsetHeight : y;
    obj.style.left = x + 'px';
    obj.style.top = y + 'px';
    $SHOW(id);
}

// 특정 엘리먼트의 코너 좌표 반환
// cornor : 0=좌측상단(기본), 1=좌측하단, 2=우측상단, 3=우측하단
function getCornorXY(id, cornor) {
    var obj = $(id);
    if (obj == null) return [0, 0];

    var x = getAbsoluteLeft(obj);
    var y = getAbsoluteTop(obj);

    cornor = cornor == undefined ? 0 : cornor;
    switch (cornor) {
        case 1: y += parseInt(obj.offsetHeight); break;
        case 2: x += parseInt(obj.offsetWidth); break;
        case 3: x += parseInt(obj.offsetWidth); y += parseInt(obj.offsetHeight); break;
        default: break;
    }

    return [x, y];
}

function showLayerImage(id, imgurl, alttext, alignx, aligny) {
    var pos = getCurrentXY();
    alignx = alignx ? alignx : 0;
    aligny = aligny ? aligny : 0;
    addLayer('tmp' + id, '', 'none', false, pos[0] + alignx, pos[1] + aligny, true, true);
    $('tmp' + id).innerHTML = '<img src="' + imgurl + '" alt="' + (alttext != undefined ? alttext : '이미지 미리보기') + '" onclick="removeLayer(\'tmp' + id + '\');" style="border:solid 1px #e6e6e6"/>';
    showLayer('tmp' + id);
}

function SelfClose() {
    try {
        if (navigator.appVersion.indexOf("MSIE 7") > -1) {
            window.open('about:blank', '_self').close();
        } else { self.opener = self; self.close(); }
    } catch (e) { self.close(); }
}

// 현재 마우스 좌표(IE/크롬/NS 호환)
function getCurrentXY() {
    try {
        var t = window.event || e;
        var tempX, tempY;
        if (t.pageX || t.pageY) {
            tempX = t.pageX;
            tempY = t.pageY;
        }
        else {
            var de = document.documentElement;
            var b = document.body;
            tempX = t.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
            tempY = t.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
        }
        return [tempX, tempY];
    }
    catch (ex) {
    }
    return [0, 0];
}

function isIEInput(event) {
    if (window.event.srcElement.tagName.toLowerCase() == "textarea" || window.event.srcElement.tagName.toLowerCase() == "input") return true; else return false;
}

function isFFInput(event) {
    if (event.target.tagName.toLowerCase() == "textarea" || event.target.tagName.toLowerCase() == "input") return true; else return false;
}

function DisableCopy() {
    var agent = new Agent();

    if (agent.isIE) window.document.oncontextmenu = isIEInput; else window.document.oncontextmenu = isFFInput;
    if (agent.isIE) window.document.onselectstart = isIEInput; else window.document.onselectstart = isFFInput;
    if (agent.isIE) window.document.ondragstart = isIEInput; else window.document.ondragstart = isFFInput;
    if (window.document.body) window.document.body.style.MozUserSelect = 'none';
}

function EnableCopy() {
    try {
        window.document.oncontextmenu = null;
        window.document.onselectstart = null;
        window.document.ondragstart = null;
        if (window.document.body) window.document.body.style.MozUserSelect = 'text';
    }
    catch (e) {
    }
}

function getXBoardListURL(bid) {
    switch (bid) {
        case 'snotice': return window.location.pathname.substr(0, window.location.pathname.indexOf('/', 1)).toLowerCase() + '/etc/snotice/List.aspx?bid=' + bid;
        case 'newsfocus': return window.location.pathname.substr(0, window.location.pathname.indexOf('/', 1)).toLowerCase() + '/etc/newsfocus/List.aspx?bid=' + bid;
        case 'spoll': return window.location.pathname.substr(0, window.location.pathname.indexOf('/', 1)).toLowerCase() + '/etc/spoll/List.aspx?bid=' + bid;

        case 'discuss': return '/expert/field/discuss/List.aspx?bid=' + bid;
        case 'qna': return '/expert/field/qna/List.aspx?bid=' + bid;
        case 'weeklycase':
        case 'case': return '/expert/field/case/List.aspx?bid=case';
        case 'pricemenu': return '/expert/field/pricemenu/default.aspx?bid=pricemenu';
        case 'knowhow': return '/expert/field/knowhow/List.aspx?bid=' + bid;
        case 'free': return '/expert/field/free/List.aspx?bid=' + bid;

        case 'circuit': return '/expert/library/circuit/List.aspx?bid=' + bid;
        case 'timingbelt': return '/expert/library/timingbelt/List.aspx?bid=' + bid;
        case 'skill': return '/expert/library/skill/List.aspx?bid=' + bid;
        case 'scope': return '/expert/library/scope/List.aspx?bid=' + bid;
        case 'scanner': return '/expert/library/scanner/List.aspx?bid=' + bid;

        case 'cobuy': return '/expert/share/cobuy/List.aspx?bid=' + bid;
        case 'guinfocus': return '/expert/share/guin/List.aspx?bid=guin';
        case 'guin': return '/expert/share/guin/List.aspx?bid=' + bid;
        case 'gujik': return '/expert/share/gujik/List.aspx?bid=' + bid;
        case 'shareshop': return '/expert/share/shareshop/List.aspx?bid=' + bid;

        case 'fnotice':
        case 'edunotice': return '/expert/forum/fnotice/List.aspx?bid=fnotice';
        case 'edufield': return '/expert/forum/education/edufield/List.aspx?bid=' + bid;

        case 'eduschedule': return '/expert/forum/education/eduschedule/List.aspx?bid=' + bid;
        case 'edusitu': return '/expert/forum/education/edusitu/List.aspx?bid=' + bid;

        case 'shopconsult': return '/owner/shopconsult/List.aspx?bid=' + bid;
        case 'shopdiary': return '/owner/shopdiary/List.aspx?bid=' + bid;
        case 'carsense': return '/owner/carsense/List.aspx?bid=' + bid;

        case 'mycar': return '/owner/mycar/List.aspx?bid=' + bid;
        case 'cargallery': return '/owner/cargallery/List.aspx?bid=' + bid;

        case 'ownersuraeshop': return '/owner/shopdiary/List.aspx?bid=shopdiary';
    }

    return '/';
}

function getXBoardAttachURL(bid) {
    switch (bid.toLowerCase()) {
        case 'weeklycase': bid = 'case'; break;
        case 'guinfocus': bid = 'guin'; break;
        case 'fnotice': bid = 'fnotice'; break;
        case 'ownersuraeshop': bid = 'shopdiary'; break;
    }

    return 'http://upload.surae.com/' + bid + '/';
}

/// 공통 게시판 링크 생성
function getXBoardLink(bid, bno, subject, title, cutlen) {
    return '<a href="' + getXBoardListURL(bid) + '&bno=' + bno + '" title="' + (title != undefined ? title.replace(/\"/g, "\"").replace(/</g, "&gt;").replace(/>/g, "&lt;") : '') + '">' + (cutlen != null && cutlen > 0 ? CutString(subject, cutlen) : subject) + '</a>';
}

function getXBoardLinkEx(bid, bno, prefix, subject, title, prefixcss, subjectcss, subjecttextspancss, cutlen) {
    return '<a ' + (subjectcss != undefined ? 'class="' + subjectcss + '" ' : '') + 'href="' + getXBoardListURL(bid) + '&bno=' + bno + '" title="' + (title != undefined ? title.replace(/\"/g, "\"").replace(/</g, "&gt;").replace(/>/g, "&lt;") : '') + '">'
        + (prefix != undefined && prefix != null && prefix != '' ? '<span' + (prefixcss != undefined && prefixcss != null ? ' class="' + prefixcss + '"' : '') + '>[' + prefix + ']</span> ' : '')
        + (subjecttextspancss != undefined ? '<span class="' + subjecttextspancss + '">' : '') + (cutlen!=null&&cutlen>0 ? CutString(subject, cutlen) : subject) + (subjecttextspancss != undefined ? '</span>' : '') + '</a>'; //.replace(/<[^\>]+>/ig,"")
}


//////////////// 수레샵 ////////////////////////////
function getSBoardListURL(sid, bid) {
    switch (bid) {
        case 'shopevent': return '/shop/event/List.aspx?shopid=' + sid + '&bid=' + bid;
        case 'shopconsult': return '/shop/consult/List.aspx?shopid=' + sid + '&bid=' + bid;

    }
    return '/';
}

function getSBoardLink(sid, bid, bno, subject, title) {
    return '<a href="' + getSBoardListURL(sid, bid) + '&bno=' + bno + '" title="' + (title != undefined ? title.replace(/\"/g, "\"").replace(/</g, "&gt;").replace(/>/g, "&lt;") : '') + '">' + subject + '</a>';
}
//////////////// 수레샵  ////////////////////////////

//// 레이어 유틸
//function showAlert(strmsg, okfn, cancelfn) {
//    var x,y,w,h;
//    var body=document.body?document.body:documentElement;
//    w=320;h=240;
//    x=((body.clientWidth-w)/2)+body.scrollLeft;
//    y=((body.clientHeight-h)/2)+body.scrollTop;
//    var div=addLayer('divAlertMsg',null,'none',true,x,y,true,false,w,h);
//    if(div==undefined){ alert(strmsg); return;}
//    div.innerHTML=strmsg;
//}

/// 공통 사용 HTML 생성 함수

// 사용자 타입
function getUserTypeText(ut) {
    switch (ut) {
        case 'D': return '운전자';
        case 'E': return '전문가';
        case 'S': return '정비소';
        default: return '기타';
    }
}
function getUserTypeImage(ut) {
    switch (ut) {
        case 'D': return '<img src="http://image.surae.com/img/Common/driver.gif" alt="운전자"/>';
        case 'E': return '<img src="http://image.surae.com/img/Common/specialist.gif" alt="전문가"/>';
        case 'S': return '<img src="http://image.surae.com/img/Common/repair.gif" alt="정비소"/>';
        default: return '';
    }
}
// 사용자 메뉴
function getUserMenuHTML(uid, uname, title, utype, viewid, max) {
    if (uid == undefined || uid.length < 1) return uname;
    return '<a href="#" onclick="ViewUserMenu(\'' + uid + '\');return false;" title="' + (title != undefined && title != null ? title : uname) + '님에 대한 메뉴">' + (utype != undefined && utype != null ? getUserTypeImage(utype) : '') + (max != undefined && max < uname.length ? uname.substr(0, max) + '…' : uname) + (viewid != undefined && viewid != null ? '(' + uid + ')' : '') + '</a>';
}
function getUserMenuHTMLCSS(uid, uname, title, utype, viewid, max) {
    if (uid == undefined || uid.length < 1) return uname;
    return '<a href="#" onclick="ViewUserMenu(\'' + uid + '\');return false;" title="' + (title != undefined && title != null ? title : uname) + '님에 대한 메뉴">' + (utype != undefined && utype != null ? getUserTypeImage(utype) : '') + ' <span class="Small62636d">' + (max != undefined && max < uname.length ? uname.substr(0, max) + '…' : uname) + (viewid != undefined && viewid != null ? '(' + uid + ')' : '') + '</span></a>';
}

/// 공통 사용 직접 호출 함수

var aErrors = {
    'unknown': '죄송합니다.\n잠시 서버 오류가 발생하여 더 이상 진행할 수 없습니다.\n잠시 후에 다시 시도해 주시거나 계속 이 오류 메시지가 나타나면 고객센터로 문의하여주세요.\n\n불편을 끼쳐드려 죄송합니다'
    , 'NOAVAIL': '로그인 후에 이용하실 수 있는 기능이거나 현재 사용하실 수 없습니다.'
    , 'NOLOGIN': '로그인 후에 이용하실 수 있는 기능입니다'
    , 'NOUSERORINVALID': '사용자ID 또는 비밀번호가 올바르지 않습니다.\n아이디 및 비밀번호의 영문자, 대소문자를 확인하신 후에 다시 로그인 버튼을 눌러주세요.'
    , 'NOUSER': '가입한 사용자가 아니거나 탈퇴한 사용자입니다'
    , 'NOARGS': '해당 기능에 필요한 옵션이 주어지지 않았습니다'
    , 'NOCMD': '실행할 기능이 지정되지 않았습니다'
    , 'NOSEND': '쪽지를 보내지 못 했습니다'
    , 'OKDEL': '쪽지를 삭제했습니다'
    , 'NODEL': '쪽지를 삭제하지 못 했습니다'
    , 'OKCC': '쪽지 발송을 취소했습니다'
    , 'NOCC': '쪽지 발송을 취소하지 못 했습니다(받는사람이 쪽지를 읽었거나 취소할 수 없습니다)'
    , 'NOGET': '읽을 쪽지가 없거나 삭제된 쪽지입니다'
    , 'MEMOOKFAIL': '쪽지를 받는 사용자 중에서 일부 사용자에게 발송하지 못했습니다'
    , 'SELFID': '자신에게는 쪽지를 보내실 수 없습니다'
    , 'SINGOOK': '게시물 신고가 완료되었습니다'
    , 'SINGONO': '게시물 신고를 하지 못했습니다'
    , 'SINGODUP': '이 게시물에 대해서 이미 신고를 하셨습니다'
    , 'SCRAPOOK': '책갈피 등록이 완료되었습니다'
    , 'SCRAPONO': '책갈피 등록을 하지 못했습니다'
    , 'SCRAPDUP': '이 게시물은 이미 책갈피에 등록되어 있습니다'
    , 'NOLIST': '표시할 내용이 없습니다'
    , 'OVER100': '검색된 사용자 또는 지인이 100명이 넘습니다.\n성명 입력하여 더 상세한 회원을 찾으실 수 있습니다'
    , 'NOUSER': '검색된 사용자 또는 등록된 지인이 없습니다'
    , 'OKSCRAP': '책갈피를 삭제했습니다'
    , 'NOSCRAP': '책갈피를 삭제하지 못 했습니다'
};

// 사용자 메뉴
function ViewUserMenu(destuid) {
    if (destuid == undefined || destuid.length < 1) return;

    var pos = getCurrentXY();
    addLayer('divUserMenu', 'Infolist', 'none', true, pos[0], pos[1], true);
    new Ajax("/ajax/member/GetUserMenu.aspx?uid=" + encodeURIComponent(destuid),
        { update: 'divUserMenu', onSuccess: function(ajax) {
            if (ajax.getResponseText().substring(0, 3) == "ER|") { try { var pose = ajax.getResponseText().indexOf("$"); alert(aErrors[ajax.getResponseText().substring(3, pose)]); } catch (e) { } return; }
            showLayer('divUserMenu');
        }, onError: function(ajax) { alert(aErrors['NOAVAIL']); }
        });
}

// 회원정보 보기
function ViewUserInfo(destuid) {
    if (destuid == undefined || destuid.length < 1) return;

    var pos = getCurrentXY();
    addLayer('divUserInfo', 'Infomember', 'none', true, pos[0], pos[1], true);
    new Ajax("/ajax/member/GetUserInfo.aspx?uid=" + encodeURIComponent(destuid),
        { update: 'divUserInfo', onSuccess: function(ajax) {
            if (ajax.getResponseText().substring(0, 3) == "ER|") { try { var pose = ajax.getResponseText().indexOf("$"); alert(aErrors[ajax.getResponseText().substring(3, pose)]); } catch (e) { } return; }
            showLayer('divUserInfo');
        }, onError: function(ajax) { alert(aErrors['NOAVAIL']); }
        });
}

// 지인 맺기
function MakeFriend(destuid) {
    if (destuid == undefined || destuid.length < 1) return;

    new Ajax("/ajax/member/MemberAjax.aspx?cmd=mf&uid=" + encodeURIComponent(destuid),
        { onSuccess: function(ajax) {
            if (ajax.getResponseText().substring(0, 3) == "ER|") { try { var pose = ajax.getResponseText().indexOf("$"); alert(aErrors[ajax.getResponseText().substring(3, pose)]); } catch (e) { } return; }

            if (ajax.getResponseText() == 'OK') { if (confirm('지인신청이 완료되었습니다.\n지인관리 페이지로 이동하시겠습니까?')) { top.location.href = '/common/myPage/friend/List.aspx?bid=friend'; } }
            else if (ajax.getResponseText() == 'NO2') { alert('이미 지인신청 상태입니다'); }
            else if (ajax.getResponseText() == 'NO3') { if (confirm('이미 지인인 회원입니다.\n지인관리 페이지로 이동하시겠습니까?')) { top.location.href = '/common/myPage/friend/List.aspx?bid=friend'; } }
            else if (ajax.getResponseText() == 'NO4') { alert('지인신청을 거절한 회원입니다'); }
            else if (ajax.getResponseText() == 'NO5') { alert('지인신청을 취소한 회원입니다'); }
            else { alert('지인 신청을 할 수 없습니다'); }
        }, onError: function(ajax) { alert(aErrors['NOAVAIL']); }
        });
}

// 쪽지 보내기
function SendMemo(flag, destuid) {
    if (destuid == undefined || destuid.length < 1) return;

    var pos = getCurrentXY();
    var posx = pos[0];
    if ((bid) && (bid == 'circuit')) { posx = posx - 250; }
    addLayer('divSendMemoLayer', 'Infomember', 'none', true, posx, pos[1], true);
    new Ajax("/ajax/memo/MemoForm.aspx?f=" + flag + "&uid=" + encodeURIComponent(destuid),
        { update: 'divSendMemoLayer', onSuccess: function(ajax) {
            if (ajax.getResponseText().substring(0, 3) == "ER|") { try { var pose = ajax.getResponseText().indexOf("$"); alert(aErrors[ajax.getResponseText().substring(3, pose)]); } catch (e) { } return; }
            showLayer('divSendMemoLayer');
        }, onError: function(ajax) { alert(aErrors['NOAVAIL']); }
        });
}

// 쪽지 가져오기
function GetMemo(mno) {
    new Ajax("/ajax/memo/MemoAjax.aspx?cmd=read&no=" + mno,
        { onSuccess: function(ajax) {
            if (ajax.getResponseText().substring(0, 3) == "ER|") { try { var pose = ajax.getResponseText().indexOf("$"); alert(aErrors[ajax.getResponseText().substring(3, pose)]); } catch (e) { } return; }
            try {
                var memo = eval('(' + ajax.getResponseText() + ')');
            } catch (e) { }
        }, onError: function(ajax) { alert(aErrors['NOAVAIL']); }
        });
}

// 쪽지 보내기 P/UID/MEMO/null/null, F/FID/MEMO/회원타입/null. S/SID/MEMO/회원타입/null
function _SendMemo(flag, destuid, content, mt, rep) {
    var data = "f=" + flag + "&id=" + encodeURIComponent(destuid) + "&mt=" + encodeURIComponent($V(mt, '')) + "&rep=" + encodeURIComponent($V(rep, '')) + "&con=" + encodeURIComponent(content.replace(/</ig, "&lt;").replace(/>/ig, "&gt;"))
    new Ajax("/ajax/memo/MemoAjax.aspx?cmd=write",
        { method: 'post', content: data, onSuccess: function(ajax) {
            if (ajax.getResponseText().substring(0, 3) == "ER|") { try { var pose = ajax.getResponseText().indexOf("$"); alert(aErrors[ajax.getResponseText().substring(3, pose)]); } catch (e) { } return; }
            if (ajax.getResponseText() == 'OK+F') { alert(aErrors['MEMOOKFAIL']); return; }
            alert('쪽지를 보냈습니다.\n(보내신 쪽지 및 읽음 여부는 마이페이지의 쪽지함에서 확인하실 수 있습니다.)');
        }, onError: function(ajax) { alert(aErrors['NOAVAIL']); }
        });
}

// 수레샵 가기
function GoMyShop() {
    window.open('/shop/init.aspx', 'shop', 'menubar=0,scrollbars=yes,width=790,height=700,top=50,left=50');
}

function GoUserShop(shopid) {
    if (shopid == undefined || shopid == '') { ViewError('ER00-02'); return; }
    var shopurl = '/shop/?shopid=' + encodeURIComponent(shopid);
    window.open(shopurl, 'shop', 'menubar=0,scrollbars=yes,width=790,height=700,top=50,left=50');
}

function GoUserShopURL(shopurl) {
    if (shopurl == undefined || shopurl == '') { ViewError('ER00-02'); return; }
    window.open(shopurl, 'shop', 'menubar=0,scrollbars=yes,width=790,height=700,top=50,left=50');
}


// 도서관(파형팝업창)
function openwin(url) {
    open(url, "scope1", "width=700,height=440,scrollbars=yes")
}
function openwin2(url) {
    open(url, "scope2", "width=718,height=550")
}
function openwin3(url) {
    open(url, "scope3", "width=620,height=550")
}


// 글자취 보기
function ViewUserBoards(destuid, destuname) {
    var x, y, w, h;
    var body = document.body ? document.body : documentElement;
    var pos = getCurrentXY();
    w = 780; h = 680;
    x = ((body.clientWidth - w) / 2) + body.scrollLeft;
    //y=((body.clientHeight-h)/2)+body.scrollTop;
    y = pos[1] + 10;
    OpenLayerPopup('Sentence', '/common/mypage/sentence/Sentence.aspx?uid=' + encodeURIComponent(destuid) + '&viw=W&una=' + encodeURIComponent(destuname), x + 'px', y + 'px', w + 'px', h + 'px', 'yes');
    $('_divSentence').className = 'Sentencepopup';
}


///
/// Layer Popup rev1.5 by wiluby, wiluby@gmail.com
///

/// Open layer popup
/// args
///     id      : id (for hide layer)
///     url     : URL
///     x       : x(left)
///     y       : y(top)
///     w       : width
///     h       : height
///     scroll  : "no", "auto", "yes"
function OpenLayerPopup(id, url, x, y, w, h, scroll) {
    try {
        var _div = document.getElementById("_div" + id);
        var _iframe = document.getElementById("_if" + id);
        var bNew = false;

        if (_div == null || _div == undefined) {
            _div = document.createElement("div");
            _iframe = document.createElement("iframe");
            _div.id = "_div" + id;
            _div.name = "_div" + id;

            _iframe.id = "_if" + id;
            _iframe.name = "_if" + id;
            bNew = true;
        }
        _div.style.position = "absolute";
        _div.style.left = x;
        _div.style.top = y;
        _div.style.width = w;
        _div.style.height = h;

        _iframe.frameBorder = 0;
        _iframe.src = url;
        _iframe.border = 0;
        _iframe.style.width = w;
        _iframe.style.height = h;

        if (scroll != null)
            _iframe.scrolling = scroll;

        if (bNew) {
            _div.appendChild(_iframe);
            document.body.appendChild(_div);
        }
    }
    catch (e) {
        alert(e.message);
    }
}

/// Hide layer popup from layer popup
function HideLayerPopup(id) {
    try {
        var bParent = false;
        var _div = document.getElementById("_div" + id);
        if (_div == undefined) { _div = parent.document.getElementById("_div" + id); if (_div != undefined) bParent = true; }
        if (_div != undefined) {
            if (bParent) parent.document.body.removeChild(_div); else document.body.removeChild(_div);
        }
    }
    catch (e) {
        alert(e.message);
    }
}

// 요약 게시물 처리
var xListData = {};

function xListInit(idDisplay, tableAttributeString, arrayHeader, visibleHeader, rowHoverColor, rowOutColor) {
    xListData[idDisplay] = { _ta: tableAttributeString, _vh: visibleHeader, _ah: arrayHeader, _rhc: rowHoverColor, _roc: rowOutColor, _bc: {} };
}

function xListResetDefault(idDisplay, searchoption) {
}

function xListSearchPage(idDisplay, pageno, searchoption) {
}

function xListBindList(idDisplay, jsonList) {
    var display = $(idDisplay);
    if (display == undefined || xListData[idDisplay] == undefined) return;

    var html = '<table ' + xListData[idDisplay]['_ta'] + '>';

    if (xListData[idDisplay]['_vh'] != undefined && xListData[idDisplay]['_vh']) {
        html += '<tr>';
        for (var n = 0; n < xListData[idDisplay]['_ah'][0].length; n++) {
            if (xListData[idDisplay]['_ah'][0][n] == null) continue;
            html += '<th' + (xListData[idDisplay]['_ah'][0][n] != '' ? ' class="' + xListData[idDisplay]['_ah'][0][n] + '"' : '') + '>' + xListData[idDisplay]['_ah'][1][n] + '</th>';
        }
        html += '</tr>';
    }

    for (var r = 0; r < jsonList.length; r++) {
        html += '<tr>';
        for (var n = 0; n < xListData[idDisplay]['_ah'][0].length; n++) {
            if (xListData[idDisplay]['_ah'][0][n] == null) continue;
            html += '<td class="' + xListData[idDisplay]['_ah'][0][n] + '">' + (
                xListData[idDisplay]['_bc'][xListData[idDisplay]['_ah'][2][n]] != undefined ?
                xListData[idDisplay]['_bc'][xListData[idDisplay]['_ah'][2][n]](r, jsonList[r])
                :
                jsonList[r][xListData[idDisplay]['_ah'][2][n]]
                ) + '</td>';
        }
        html += '</tr>';
    }

    html += '</table>';

    display.innerHTML = html;
}

function xListBindListUL(idDisplay, jsonList, rowliattr, fnrowbind) {
    var display = $(idDisplay);
    if (display == undefined || xListData[idDisplay] == undefined) return;

    var html = '<ul ' + xListData[idDisplay]['_ta'] + '>';

    for (var r = 0; r < jsonList.length; r++) {
        html += '<li ' + $V(rowliattr, '') + '>' + fnrowbind(r, jsonList[r]) + '</li>';
    }

    html += '</ul>';

    display.innerHTML = html;
}

function xListBindListCustom(idDisplay, jsonList, fnrowbind) {
    var display = $(idDisplay);
    if (display == undefined || xListData[idDisplay] == undefined) return;

    var html = '';

    for (var r = 0; r < jsonList.length; r++) {
        html += fnrowbind(r, jsonList[r]);
    }

    display.innerHTML = html;
}

function xListBindColumn(idDisplay, columnID, fnMakeColumn) {
    xListData[idDisplay]['_bc'][columnID] = fnMakeColumn;
}

// 요청된 카테고리의 목록을 ajax로 받아옴
function xListRequest(idDisplay, ryn, summaryid, flag, rows) {
    if (flag == undefined || summaryid == undefined || rows == undefined) return;

    new Ajax("/ajax/summary/GetSummary.aspx?rt=" + (ryn ? 1 : 0) + "&s=" + summaryid + "&f=" + flag + "&r=" + rows, { tag: idDisplay, onSuccess: function(ajax) {
        try {
            var _tmp = eval('(' + ajax.getResponseText() + ')');
            xListBindList(ajax.tag, _tmp);
        } catch (e) {
            alert(e);
        }
    }, onError: function(ajax) { alert(aErrors['unknown']); }
    });
}
// 요청된 카테고리의 목록을 ajax로 받아옴
function xListRequestUL(idDisplay, ryn, summaryid, rowliattr, fnrowbind, flag, rows) {
    if (flag == undefined || summaryid == undefined || rows == undefined) return;

    new Ajax("/ajax/summary/GetSummary.aspx?rt=" + (ryn ? 1 : 0) + "&s=" + summaryid + "&f=" + flag + "&r=" + rows, { onSuccess: function(ajax) {
        try {
            var _tmp = eval('(' + ajax.getResponseText() + ')');
            xListBindListUL(idDisplay, _tmp, rowliattr, fnrowbind);
        } catch (e) {
            alert(e);
        }
    }, onError: function(ajax) { alert(aErrors['unknown']); }
    });
}
// 요청된 카테고리의 목록을 ajax로 받아옴
function xListRequestCustom(idDisplay, ryn, summaryid, fnrowbind, flag, rows) {
    if (flag == undefined || summaryid == undefined || rows == undefined) return;

    new Ajax("/ajax/summary/GetSummary.aspx?rt=" + (ryn ? 1 : 0) + "&s=" + summaryid + "&f=" + flag + "&r=" + rows, { onSuccess: function(ajax) {
        try {
            var _tmp = eval('(' + ajax.getResponseText() + ')');
            xListBindListCustom(idDisplay, _tmp, fnrowbind);
        } catch (e) {
            alert(e);
        }
    }, onError: function(ajax) { alert(aErrors['unknown']); }
    });
}

function getDisplayID_SummaryTitle(summaryid) { return 'divSummary' + summaryid; }
function getAnchorID_SummaryMore(summaryid) { return 'aSummaryMore' + summaryid; }
function getDisplayID_SummaryList(summaryid) { return 'divSummaryList' + summaryid; }
function getDisplayID_SummaryBottom(summaryid) { return 'divSummaryBottom' + summaryid; }

function showPageNavi(idObj, totalpage, curpage, cntperpage, fnname) {
    var idDisplay = $(idObj);

    if (idDisplay == undefined) return;

    var html = '';

    if (totalpage < 1 || curpage < 1) return '';

    html = '<a href="#" title="처음으로" onclick="' + fnname + '(1); return false;"><<</a>'
        + ' <a href="#" title="이전으로" onclick="' + fnname + '(' + (curpage - cntperpage > 1 ? curpage - cntperpage : 1) + '); return false;"><</a> ';

    var sp = parseInt(curpage - ((curpage - 1) % cntperpage));

    for (var n = 0; n < cntperpage && n + sp <= totalpage; n++) {
        html += '<a class="' + (sp + n == curpage ? 'PagelistC' : 'Pagelist') + '" href="#" onclick="' + fnname + '(' + (sp + n) + '); return false;">' + (sp + n) + '</a>';
    }

    html += ' <a href="#" title="다음으로" onclick="' + fnname + '(' + (sp + cntperpage < totalpage ? sp + cntperpage : totalpage) + '); return false;">></a>'
        + ' <a href="#" title="마지막으로"onclick="' + fnname + '(' + totalpage + '); return false;">>></a>';

    idDisplay.innerHTML = html;
}

// 목록 처리(0:css, 1:header text, 2:columnid) - 표시 제외시 css를 null로, 순서는 출력순
var xListHeaderCommon = [
		[null, null, null, null, null, 'cssSubject', 'cssUser', null, null, null, null, null, null]
		, ['SID', 'TYN', 'BID', '번호', '작성자ID', '제목', '작성자', '태그', '카운트', '플래그', '이미지파일', '작성일', '생성일']
		, ['SummaryID', 'TempYN', 'BID', 'BNo', 'UID', 'Subject', 'UName', 'SMPrefix', 'SMCount', 'SMFlag', 'SMImageFile', 'CreateDT', 'SummaryDT']
		];

var xListHeaderCommonLeft = [
		[null, null, 'cssSubject', null]
		, ['BID', '번호', '제목', '대상']
		, ['BID', 'BNo', 'Subject', 'TargetPage']
		];

var xListHeaderCommonULLeft = [
		['']
		, ['제목']
		, ['Subject']
		];

function bindCommonSubject(rowno, row) { return getXBoardLink(row['BID'], row['BNo'], row['Subject'], row['Subject']); }
function bindCommonUser(rowno, row) { return getUserMenuHTML(row['UID'], row['UName']); }
function bindCommonLeftSubject(rowno, row) { return getXBoardLink(row['BID'], row['BNo'], row['Subject'], row['Subject']); }

function xViewBindMakeDiv(id, jsondata) {
    return '<div id="xView' + id + '"></a>';
}
function xViewBindView(idDisplay, head, tail, header, jsondata) {
    var n = 0;
    if (header == undefined || jsondata == undefined) { alert('표시할 데이터가 없습니다.'); return; }
    var html = head;
    for (var key in header[1]) {
        if (n == 0) html += '<tr>';
        html += '<td ' + (header[0][n] != undefined ? header[0][n] : '') + '>' + header[1][key].text + '</td><td cols="' + header[1][key].cols + '" ' + (header[0][n + 1] != undefined ? header[0][n + 1] : '') + '>';
        if (header[2][key] != undefined) { html += header[2][key](key, jsondata); } else { html += jsondata[0][key]; }
        html += '</td>';
        n += header[1][key].cols + 1; if (n >= header[0].length) { html += '</tr>'; n = 0; }
    }
    html += tail;
    $(idDisplay).innerHTML = html;
}

// 인자:대상UID,대상UName,대상글제목,영역(B,F,S),대상글BNo
function showSingo(destuid, destuname, destsubject, flag, destbno) {
    if (destuid == undefined || destuid.length < 1 || destuname == undefined || destuname.length < 1
        || destsubject == undefined || destsubject.length < 1 || flag == undefined || flag.length < 1 || destbno == undefined || parseInt(destbno, 10) < 1) return;

    var pos = getCurrentXY();
    addLayer('divSingoForm', 'Statement', 'none', true, pos[0], pos[1], true);
    new Ajax("/ajax/xb/SingoForm.aspx?did=" + encodeURIComponent(destuid) + "&dname=" + encodeURIComponent(destuname) + "&dsub=" + encodeURIComponent(destsubject) + "&f=" + flag + "&bno=" + destbno,
        { update: 'divSingoForm', onSuccess: function(ajax) {
            if (ajax.getResponseText().substring(0, 3) == "ER|") { try { var pose = ajax.getResponseText().indexOf("$"); alert(aErrors[ajax.getResponseText().substring(3, pose)]); } catch (e) { } return; }
            showLayer('divSingoForm');
        }, onError: function(ajax) { alert(aErrors['NOAVAIL']); }
        });
}

function sendSingo(flag, bno) {
    if (bno == undefined || bno < 1) return;
    var stype = $GETRDO('rdoSingoType');
    var scomment = $('txtSingoComment');

    if (stype == undefined || stype.length < 1 || scomment == undefined || scomment.value.length < 1) {
        alert('신고사유 또는 신고 내용을 입력해주세요'); return;
    }

    var data = "f=" + flag + "&bno=" + bno + "&st=" + encodeURIComponent(stype) + "&sc=" + encodeURIComponent(scomment.value);

    new Ajax("/ajax/xb/XBoardAjax.aspx?cmd=sendsingo", { method: 'post', content: data, onSuccess: function(ajax) {
        if (ajax.getResponseText().substring(0, 3) == "ER|") { try { var pose = ajax.getResponseText().indexOf("$"); alert(aErrors[ajax.getResponseText().substring(3, pose)]); } catch (e) { } return; }
        if (ajax.getResponseText() == "OK") { alert(aErrors['SINGOOK']); hideLayer('divSingoForm'); return; }
        alert(aErrors['NOAVAIL']);
    }, onError: function(ajax) { alert(aErrors['NOAVAIL']); }
    });
}

function showPartnership() {
    var pos = getCurrentXY();
    addLayer('PartnershipForm', 'Partnership', 'none', false, pos[0], pos[1] - 150 > 0 ? pos[1] - 150 : pos[1], true);
    new Ajax("/ajax/partnership/PartnershipForm.aspx",
        { update: 'PartnershipForm', evalScript: true, onSuccess: function(ajax) {
            if (ajax.getResponseText().substring(0, 3) == "ER|") { try { var pose = ajax.getResponseText().indexOf("$"); alert(aErrors[ajax.getResponseText().substring(3, pose)]); } catch (e) { } return; }
            showLayer('PartnershipForm');
        }, onError: function(ajax) { alert(aErrors['NOAVAIL']); }
        });
}

// Linked Select
// html select element를 대신할 수 있는 Select Ajax Javascript
// tested under IE6/IE7/IE8betarc1/Chrome

var arrSelectBoxList = {}; // 기본 값 처리

/// (내부)기본 selectbox의 선택 layer 생성 및 스타일 지정
function initSelectBox(id, cssclass) {
    var _divSelectList = $('divSelectList' + id);
    if (_divSelectList == undefined) {
        _divSelectList = document.createElement("DIV");
        _divSelectList.id = 'divSelectList' + id;
        if (cssclass.length > 1) {
            _divSelectList.className = cssclass;
        }
        else {
            _divSelectList.style.backgroundColor = 'white';
            _divSelectList.style.position = 'absolute';
        }
        _divSelectList.style.zIndex = '9999';
        _divSelectList.style.display = 'none';

        document.body.appendChild(_divSelectList);
        addAutoHide(id, 'divSelectList' + id);

        // for IE6 with SELECT tag
        if (navigator.userAgent.indexOf("MSIE 6") > -1) {
            var objIF = $('divSelectListIF' + id);
            if (objIF == undefined) {
                objIF = document.createElement('iframe');
                objIF.id = 'divSelectListIF' + id;
                objIF.style.backgroundColor = 'blue';
                objIF.style.position = 'absolute';
                objIF.style.opacity = '0';
                objIF.style.filter = 'alpha(opacity=0)';
                objIF.style.zIndex = '9998';
                objIF.style.left = '0px';
                objIF.style.top = '0px';
                objIF.style.width = _divSelectList.offsetWidth;
                objIF.style.height = _divSelectList.offsetHeight;
                document.body.appendChild(objIF);
                addAutoHide(id + 'IF', 'divSelectListIF' + id);
            }
        }
    }
    else {
        $HIDEB('divSelectList' + id);
        if (navigator.userAgent.indexOf("MSIE 6") > -1) { $HIDEB('divSelectListIF' + id); }
    }

    return _divSelectList;
}

/// Select 추가
// id : 추가될 select box id
// cssclass : select list의 기본 style class id 없으면 자동 지정
// defaulttext : 기본 텍스트
// defaultvalue : 기본 값
// initvalue : 기본 선택 값(immediate값이 무조건 true 설정)
// fnBeforeClick : select box 클릭시 호출
// fnAfterSelect : 선택 후 호출될 함수
// fnAfterCancel : 취소(선택안함) 후 호출될 함수
// x : 표시 x 좌표(0이면 해당 id의 x위치)
// y : 표시 y 좌표(0이면 해당 id의 바로 아래)
// immediate : 즉시 목록 가져올 것인지(true/false) 기본 : false
// loadonce : 한번만 로드할 것인지(true/false) 기본 : false
// fnEmptyList : 빈값 선택 시 처리 함수
// reset : (기본 false) 재사용될 경우, 비정상 동작 시 true(true/false) ex)웹페이지에 동적으로 추가/삭제되는 곳에서 항상 true
// noselect : 선택없음 표시 여부(true면 표시, false면 미표시, 기본 false)
// fnDefaultOK : defaultvalue가 주어졌을 때, 완료 후 호출됨
function addSelectBox(id, cssclass, defaulttext, defaultvalue, initvalue, fnBeforeClick, fnAfterSelect, fnAfterCancel, x, y, immediate, loadonce, fnEmptyList, reset, noselect, fnDefaultOK) {
    var divSelect = $(id);
    if (divSelect == undefined)
        return;
    if (arrSelectBoxList[id] != undefined) { if (reset != undefined && reset) { delete arrSelectBoxList[id]; arrSelectBoxList[id] = null; } else return; }

    if (defaulttext == undefined || defaulttext == null || defaulttext == '') defaulttext = '선택없음';
    if (defaultvalue == undefined || defaultvalue == null || defaultvalue == '') defaultvalue = '';
    if (x == undefined) x = 0;
    if (y == undefined) y = 0;
    if (immediate == undefined) immediate = false;
    if (loadonce == undefined) loadonce = false;

    divSelect.innerHTML = defaulttext;

    addEvent(divSelect, 'click', function() { callBeforeClick(id); });

    immediate = (initvalue != undefined && initvalue.length > 0) ? true : immediate;

    // selectbox등록
    arrSelectBoxList[id] = { ele: id, b: fnBeforeClick, s: fnAfterSelect, c: fnAfterCancel, et: fnEmptyList, dt: defaulttext, dv: defaultvalue, iv: initvalue, nv: initvalue, ss: cssclass, i: immediate, o: loadonce, posx: x, posy: y, loaded: false, enable: true, nosel: noselect, okv: '', ds: fnDefaultOK };

    // 즉시로드 가동
    if (immediate) callBeforeClick(id);
}

// (내부)선택 후 처리
function callSelecting(id, text, value) {
    var fn = arrSelectBoxList[id]['s'];
    hideSelectBoxList(id);
    var div = $(id);
    if (div != undefined) { div.innerText = text; arrSelectBoxList[id]['nv'] = value; }
    if (fn != undefined) fn(id, text, value);
}

// (내부)선택 클릭시
function callBeforeClick(id) {
    if (arrSelectBoxList[id] != undefined && arrSelectBoxList[id]['enable'] != undefined && !arrSelectBoxList[id]['enable']) return;
    var loadonce = arrSelectBoxList[id]['o'];
    var loaded = arrSelectBoxList[id]['loaded'];
    hideAllSelectList();
    if (loadonce != undefined && loadonce && loaded != undefined && loaded) {
        var cssid = arrSelectBoxList[id]['ss'];
        var div = $(id);
        var divSelectList = initSelectBox(id, cssid != undefined ? cssid : '');
        if (div == undefined || divSelectList == undefined) return;
        var x = arrSelectBoxList[id]['posx']; x = x != undefined ? x : 0;
        var y = arrSelectBoxList[id]['posy']; y = y != undefined ? y : 0;
        if (x >= 0) divSelectList.style.left = x == 0 ? (getAbsoluteLeft(div) - div.offsetWidth) + 'px' : x + 'px';
        if (y >= 0) divSelectList.style.top = y == 0 ? (getAbsoluteTop(div) + div.offsetHeight) + 'px' : y + 'px';
        showSelectBoxList(id); return;
    }
    var fn = arrSelectBoxList[id]['b'];
    if (fn != undefined) fn(id);
}

// (내부)선택안함 처리
function callCanceling(id) {
    var fn = arrSelectBoxList[id]['c'];
    hideSelectBoxList(id);
    if (fn != undefined) fn(id);
}

/// selectbox의 텍스트와 값 설정(이 설정값을 selectbox가 보호하지 않아서 변경되면 사라짐)
function setSelectBoxValue(id, text, value) {
    var div = $(id);
    if (div != undefined) { div.innerHTML = text; arrSelectBoxList[id]['nv'] = value }
}

function setSelectBoxValue2(id, value) {
    if (arrSelectBoxList[id] != undefined) {
        arrSelectBoxList[id]['i'] = true;
        arrSelectBoxList[id]['okv'] = value;
        callBeforeClick(id);
    }
}

/// selectbox의 선택된 텍스트
function getSelectBoxText(id) {
    if (arrSelectBoxList[id] == undefined) return '';
    var div = $(id);
    if (div != undefined) { return div.innerHTML; }
    var v = arrSelectBoxList[id]['dt'];
    return v != undefined ? v : '';
}

/// selectbox의 선택된 값
function getSelectBoxValue(id) {
    if (arrSelectBoxList[id] == undefined) return '';
    var nv = $V(arrSelectBoxList[id]['nv'], '');
    if (nv.length > 0) { return nv; }
    var v = arrSelectBoxList[id]['dv'];
    return v != undefined ? v : '';
}

// selectbox의 기본값으로 설정
function resetSelectBox(id) {
    if (arrSelectBoxList[id] == undefined) return;
    var div = $(id);
    var dt = arrSelectBoxList[id]['dt']; dt = dt != undefined ? dt : '';
    var dv = arrSelectBoxList[id]['dv']; dv = dv != undefined ? dv : '';
    if (div != undefined) { div.innerText = dt; arrSelectBoxList[id]['nv'] = dv; }
}

function enableSelectBox(id) {
    try {
        if (arrSelectBoxList[id]['enable'] == undefined || arrSelectBoxList[id]['enable']) return;

        var div = $(id);
        arrSelectBoxList[id]['enable'] = true;
        div.style.color = arrSelectBoxList[id]['oldc'];
    } catch (e) {
        alert(e);
    }
}

function disableSelectBox(id) {
    try {
        if (arrSelectBoxList[id]['enable'] == undefined || !arrSelectBoxList[id]['enable']) return;

        var div = $(id);
        arrSelectBoxList[id]['enable'] = false;
        arrSelectBoxList[id]['oldc'] = div.style.color;
        div.style.color = '#c6c6c6';
    } catch (e) {
        alert(e);
    }
}

/// 열려있는 모든 selectbox list를 감춘다.
function hideAllSelectList() {
    for (var i in arrSelectBoxList) {
        hideSelectBoxList(i);
    }
}

function showSelectBoxList(id) {
    if (navigator.userAgent.indexOf("MSIE 6") > -1) {
        var objIF = $('divSelectListIF' + id);
        var obj = $('divSelectList' + id);
        $SHOWB('divSelectList' + id);
        if (obj != undefined && objIF != undefined) {
            objIF.style.left = obj.style.left;
            objIF.style.top = obj.style.top;
            objIF.style.width = obj.offsetWidth;
            objIF.style.height = obj.offsetHeight;
            $SHOWB('divSelectListIF' + id);
            return;
        }
    }
    $SHOWB('divSelectList' + id);
}

function hideSelectBoxList(id) {
    if (navigator.userAgent.indexOf("MSIE 6") > -1) { $HIDEB('divSelectListIF' + id); }
    $HIDEB('divSelectList' + id);

}

// selectbox 보이기
function showSelectBox(id) { $(id).style.display = 'block'; }
// selectbox 감추기
function hideSelectBox(id) { $(id).style.display = 'none'; }

/// Select list 표시
// id : select box id
// cols : 한줄 표시 컬럼수
// xml : xml doc
function displaySelectList(id, cols, xml, nomsg) {
    //초기화 처리
    var cssid = arrSelectBoxList[id]['ss'];
    var divSelectList = initSelectBox(id, cssid != undefined ? cssid : '');
    var x = arrSelectBoxList[id]['posx']; x = x != undefined ? x : 0;
    var y = arrSelectBoxList[id]['posy']; y = y != undefined ? y : 0;
    var div = $(id);

    if (div == undefined || divSelectList == undefined) return;

    arrSelectBoxList[id]['loaded'] = true;

    if (x >= 0) divSelectList.style.left = x == 0 ? (getAbsoluteLeft(div) - div.offsetWidth) + 'px' : x + 'px';
    if (y >= 0) divSelectList.style.top = y == 0 ? (getAbsoluteTop(div) + div.offsetHeight) + 'px' : y + 'px';

    var items = xml.getElementsByTagName("item");

    //rows=rows>0?rows:1;
    if (items != null && items.length > 0) {
        //var cols=Math.ceil((items.length+1)/rows);
        var col = 0;
        var it = '';
        var iv = arrSelectBoxList[id]['okv'] != undefined && arrSelectBoxList[id]['okv'].length > 0 ? arrSelectBoxList[id]['okv'] : (arrSelectBoxList[id]['iv'] != undefined && arrSelectBoxList[id]['iv'].length > 0) ? arrSelectBoxList[id]['iv'] : '';
        var grp = '';
        var grpcount = 0;
        var grpstr = '';
        var str = '';
        str = "<table id=\"tblSelectList" + id + "\">";
        for (var n = 0; n < items.length; n++) {
            if (cols == 1) {
                //  javascript:alert($('divSelectListVehType').innerHTML);

                //grp가 없고, 그룹이 없는 경우
                //grp가 없고, 그룹이 있을 경우(새그룹 시작)
                //grp가 있고, 이전과 같은 grp이면

                //grp가 있고, 이전과 그룹과 다르면 새로운 row생성
                //grp가 있고, 그룹이 없는 경우(이전 그룹 닫기)
                if (n == 0 && arrSelectBoxList[id]['nosel']) str += "<td nowrap><a href=\"javascript:callCanceling('" + id + "');\"><span class='Boldred'>선택안함</span></a></td></td></tr>";

                if ((grp != '' && getNodeAttrValue(items[n], 1) == '') || (grp != getNodeAttrValue(items[n], 1))) {
                    if (grpcount > 0 && grpstr != '') str += "<tr><td nowrap>" + grp + "</td>" + grpstr;
                    grp = ''; grpcount = 0; grpstr = '';
                }

                if (getNodeAttrValue(items[n], 1) == '') {
                    str += "<tr><td nowrap><a href=\"javascript:callSelecting('" + id + "','" + getNodeValue(items[n]) + "','" + getNodeAttrValue(items[n], 0) + "');\" title=\"" + getNodeValue(items[n]) + "\">" + getNodeValue(items[n]) + "</a></td><td></td></tr>";
                }
                else if (grp != '' && grp == getNodeAttrValue(items[n], 1)) {
                    grpcount++;
                    grpstr += "<tr><td></td><td nowrap><a href=\"javascript:callSelecting('" + id + "','" + getNodeValue(items[n]) + "','" + getNodeAttrValue(items[n], 0) + "');\" title=\"" + getNodeValue(items[n]) + "\">" + getNodeValue(items[n]) + "</a></td></tr>";
                }
                else if (getNodeAttrValue(items[n], 1) != '' || grp != getNodeAttrValue(items[n], 1)) {
                    grp = getNodeAttrValue(items[n], 1); grpcount = 1;
                    grpstr += "<td nowrap><a href=\"javascript:callSelecting('" + id + "','" + getNodeValue(items[n]) + "','" + getNodeAttrValue(items[n], 0) + "');\" title=\"" + getNodeValue(items[n]) + "\">" + getNodeValue(items[n]) + "</a></td></tr>";
                }

                if (iv.length > 0 && getNodeAttrValue(items[n], 0) == iv) it = getNodeValue(items[n]);
                col = 0;
                continue;
            }
            else {
                if (col == 0)
                    str += "<tr>";
                if (n == 0 && col == 0 && arrSelectBoxList[id]['nosel']) {
                    str += "<td nowrap><a href=\"javascript:callCanceling('" + id + "');\"><span class='Boldred'>선택안함</span></a></td>";
                    col++; if (col == cols) { str += "</tr><tr>"; col = 0; } // limit cols
                }
                str += "<td nowrap><a href=\"javascript:callSelecting('" + id + "','" + getNodeValue(items[n]) + "','" + getNodeAttrValue(items[n], 0) + "');\" title=\"" + getNodeValue(items[n]) + "\">"
                    + getNodeValue(items[n]) + "</a></td>";
                if (iv.length > 0 && getNodeAttrValue(items[n], 0) == iv) it = getNodeValue(items[n]);
                // limit cols
                col++; if (col == cols) { str += "</tr>"; col = 0; }
            }
        }
        if (cols == 1) {
            if (grpcount > 0 && grpstr != '') str += "<tr><td nowrap rows=\"" + grpcount + "\">" + grp + "</td>" + grpstr;
        }
        str += "</table>";
        divSelectList.innerHTML = str;
        if (arrSelectBoxList[id]['i'] != undefined && arrSelectBoxList[id]['i']) {
            if (it.length > 0 && iv.length > 0) {
                div.innerHTML = it; arrSelectBoxList[id]['nv'] = iv;
                if (typeof arrSelectBoxList[id]['ds'] == 'function') arrSelectBoxList[id]['ds'](id);
            } arrSelectBoxList[id]['i'] = false; return;
        }
        else {
            // 즉시 로드는 보여주지 않음
            showSelectBoxList(id);
            if (cols > 1) {
                var objOrig = $(id);
                var objTable = $('tblSelectList' + id);
                var len = objTable.rows[0].cells.length;
                if (objTable == undefined || len < 1) return;
                for (var tn = 0; tn < len; tn++) {
                    if (objTable.rows[0].cells[tn].offsetWidth < objOrig.offsetWidth)
                        objTable.rows[0].cells[tn].style.width = objOrig.offsetWidth + 'px';
                }
            }
        }
    }
    else {
        var fn = arrSelectBoxList[id]['et'];
        if (fn != undefined && fn != null) { fn(id); } else { divSelectList.innerHTML = nomsg != undefined ? nomsg : "선택하실 수 있는 항목이 없습니다."; showSelectBoxList(id); }
    }
}
/// Select list 표시(서버 콜백없이 문자열 바인딩)
// id : select box id
// cols : 한줄 표시 컬럼수
// array string : "0|1|2|3|4"
// 용도예) 전화번호 국번 등(010|011|016|017) or 회원(전문가:E|정비소:S)
function displaySelectListArray(id, cols, arrstr, nomsg) {
    //초기화 처리
    var cssid = arrSelectBoxList[id]['ss'];
    var divSelectList = initSelectBox(id, cssid != undefined ? cssid : '');
    var x = arrSelectBoxList[id]['posx']; x = x != undefined ? x : 0;
    var y = arrSelectBoxList[id]['posy']; y = y != undefined ? y : 0;
    var div = $(id);
    var arrayList = arrstr.split('|');
    if (div == undefined || divSelectList == undefined) return;

    arrSelectBoxList[id]['loaded'] = true;

    if (x >= 0) divSelectList.style.left = x == 0 ? (getAbsoluteLeft(div) - div.offsetWidth) + 'px' : x + 'px';
    if (y >= 0) divSelectList.style.top = y == 0 ? (getAbsoluteTop(div) + div.offsetHeight) + 'px' : y + 'px';

    if (arrayList != undefined && arrayList.length > 0) {
        var col = 0;
        var it = '';
        var iv = (arrSelectBoxList[id]['iv'] != undefined && arrSelectBoxList[id]['iv'].length > 0) ? arrSelectBoxList[id]['iv'] : '';
        var grp = '';
        var grpcount = 0;
        var grpstr = '';
        var str = '';
        str = "<table id=\"tblSelectList" + id + "\">";
        for (var n = 0; n < arrayList.length; n++) {
            if (col == 0)
                str += "<tr>";
            if (n == 0 && col == 0 && arrSelectBoxList[id]['nosel']) {
                str += "<td nowrap><a href=\"javascript:callCanceling('" + id + "');\"><span class='Boldred'>선택안함</span></a></td>";
                col++; if (col == cols) { str += "</tr><tr>"; col = 0; } // limit cols
            }
            var arr = arrayList[n].split(':', 2);
            var text = arr.length > 1 ? arr[0] : arrayList[n];
            var value = arr.length > 1 ? arr[1] : arrayList[n];
            str += "<td nowrap><a href=\"javascript:callSelecting('" + id + "','" + text + "','" + value + "');\" title=\"" + text + "\">" + text + "</a></td>";
            if (iv.length > 0 && value == iv) it = text;
            // limit cols
            col++; if (col == cols) { str += "</tr>"; col = 0; }
        }
        str += "</table>";
        divSelectList.innerHTML = str;
        if (arrSelectBoxList[id]['i'] != undefined && arrSelectBoxList[id]['i']) {
            if (it.length > 0 && iv.length > 0) {
                div.innerHTML = it; arrSelectBoxList[id]['nv'] = iv;
                if (typeof arrSelectBoxList[id]['ds'] == 'function') arrSelectBoxList[id]['ds'](id);
            } arrSelectBoxList[id]['i'] = false; return;
        }
        else {
            // 즉시 로드는 보여주지 않음
            showSelectBoxList(id);
            if (cols > 1) {
                var objOrig = $(id);
                var objTable = $('tblSelectList' + id);
                var len = objTable.rows[0].cells.length;
                if (objTable == undefined || len < 1) return;
                for (var tn = 0; tn < len; tn++) {
                    if (objTable.rows[0].cells[tn].offsetWidth < objOrig.offsetWidth)
                        objTable.rows[0].cells[tn].style.width = objOrig.offsetWidth + 'px';
                }
            }
        }
    }
    else {
        var fn = arrSelectBoxList[id]['et'];
        if (fn != undefined && fn != null) { fn(id); } else { divSelectList.innerHTML = nomsg != undefined ? nomsg : "선택하실 수 있는 항목이 없습니다."; showSelectBoxList(id); }
    }
}

// 파일 업로드 처리
//
// Eugene Song, wiluby@gmail.com / wiluby@surae.com
//

var fileUploadMAX = {}; // 최대 업로드 지정

//첨부파일 사용 초기화
// uiid는 첨부파일 UI가 표시될 div 태그의 ID 값
// max 최대업로드 수 지정
// css iframe css class previewimg:true/false, previewfnname:prototype(uiid, previewurl, w, h)
// 업로드 확장자 ex) .jpg|.jpeg|.png|.gif
function InitFileUpload(uiid, max, cssclass, previewimg, previewfnname, allowext, ssl) {
    var display = document.getElementById(uiid);

    if (display == undefined || display == null)
        return;

    display.style.overflow = 'hidden';
    display.style.height = 24 + 'px';

    var divInfo = document.createElement("div");
    divInfo.id = "divInfo" + uiid;
    divInfo.name = "divInfo" + uiid;

    var inpFiles = document.createElement("input");
    inpFiles.id = "hidFiles" + uiid;
    inpFiles.name = "hidFiles" + uiid;
    inpFiles.type = "hidden";
    inpFiles.style.display = "none";

    var ifAttach = document.createElement("iframe");
    ifAttach.id = "ifAttachAdd" + uiid;
    ifAttach.name = "ifAttachAdd" + uiid;
    ifAttach.frameBorder = '0px';
    ifAttach.src = '/ajax/FileUpload/FileUpload.aspx?fn=' + encodeURIComponent('AddedAttachFile') + '&ii=' + encodeURIComponent(divInfo.id) + '&fi=' + encodeURIComponent(inpFiles.id) + '&lmt=' + (allowext != undefined && allowext != null ? encodeURIComponent(allowext) : '') + (ssl == 'Y' ? '&ssl=Y' : '');
    ifAttach.border = '0px';
    ifAttach.style.width = "100%";
    ifAttach.scrolling = "no";
    ifAttach.className = cssclass != undefined && cssclass != null ? cssclass : 'fileupload';

    fileUploadMAX["divInfo" + uiid] = { id: uiid, mc: (max == undefined || max == null ? 32765 : max), nc: 0, pv: (previewimg != undefined && previewimg != null ? previewimg : true), fn: previewfnname };

    display.appendChild(divInfo);
    display.appendChild(ifAttach);
    display.appendChild(inpFiles);
}

//파일 업로드 정보 삭제
function ResetFileUpload(uiid) {
    var display = document.getElementById(uiid);
    var objDisplay = document.getElementById("divInfo" + uiid);
    var objAttach = document.getElementById("hidFiles" + uiid);
    var objIFrame = document.getElementById("ifAttachAdd" + uiid);

    if (display == undefined)
        return;

    if (objDisplay != undefined)
        display.removeChild(objDisplay); //objDisplay.innerText = '';
    if (objAttach != undefined)
        display.removeChild(objAttach); //objAttach.value = '';
    if (objIFrame != undefined)
        display.removeChild(objIFrame);

    InitFileUpload(uiid);
}

//첨부파일 추가 처리
function AddedAttachFile(infoid, fileid, key, filename, filesize, mimetype, imagewidth, imageheight, tempurl, ssl) {
    var objDisplay = document.getElementById(infoid);
    var objAttach = document.getElementById(fileid);

    // 이미 추가된 파일 여부
    var objExist = document.getElementById("atttabl" + filename);
    if (objExist != undefined) {
        // 이미 추가되었으나 삭제된 파일 => 복구
        if (objExist.style.display == 'none') {
            objExist.style.height = '32px';
            objExist.style.display = 'block';
            if (objAttach.value.length > 0) objAttach.value += ",";
            objAttach.value += key; //filename+"|"+filesize+ "|"+mimetype+"|"+imagewidth+ "|"+imageheight;

            fileUploadMAX[infoid]['nc']++;
            if (fileUploadMAX[infoid]['nc'] >= fileUploadMAX[infoid]['mc']) {
                var o = $(fileUploadMAX[infoid]['id']); if (o != undefined) $HIDEB('ifAttachAdd' + fileUploadMAX[infoid]['id']);
            }

            objDisplay.style.height = (32 * fileUploadMAX[infoid]['nc']) + 'px';
            objDisplay.parentNode.style.height = (32 * fileUploadMAX[infoid]['nc']) + 24 + 'px';
            return;
        }

        alert('이미 업로드된 파일입니다');
        return;
    }

    if (objAttach.value.length > 0) objAttach.value += ",";
    objAttach.value += key; //filename+"|"+filesize+ "|"+mimetype+"|"+imagewidth+ "|"+imageheight;

    var data = '<span id="atttabl' + filename + '" style="padding-left:5px;padding-right:5px;height:32px;display:block;">';
    data += '<span style="width:32px;padding-left:5px;padding-right:5px;">' + (imagewidth > 0 && fileUploadMAX[infoid]['pv'] ? '<img src="' + tempurl + '" alt="첨부 이미지" width="32" height="32"/>' : '') + '</span><span style="text-align:left;padding-left:5px;padding-right:5px;">▶ ' + filename + ' (' + filesize + ' bytes)</span>';
    data += '<span style="width:48px;text-align:left;padding-left:5px;padding-right:5px;">';
    if (ssl == "Y")
        data += '<img src="https://image.surae.com/img/fileupload/icon/delete.gif" alt="첨부파일 삭제" onclick="DeleteAttach(\'' + infoid + '\',\'' + fileid + '\',\'' + key + '\',\'' + filename + '\');" style="cursor:pointer;"/></span>';
    else
        data += '<img src="http://image.surae.com/img/fileupload/icon/delete.gif" alt="첨부파일 삭제" onclick="DeleteAttach(\'' + infoid + '\',\'' + fileid + '\',\'' + key + '\',\'' + filename + '\');" style="cursor:pointer;"/></span>';
    data += '</span>';

    //if(objDisplay.innerHTML.length>0)data='<br/>'+data;
    objDisplay.innerHTML += data;
    if (imagewidth > 0 && imageheight > 0 && fileUploadMAX[infoid]['fn'] != undefined && fileUploadMAX[infoid]['fn'] != null) { eval(fileUploadMAX[infoid]['fn'] + '(\'' + fileUploadMAX[infoid]['id'] + '\',\'' + tempurl + '\',' + imagewidth + ',' + imageheight + ')'); }
    fileUploadMAX[infoid]['nc']++;
    if (fileUploadMAX[infoid]['nc'] >= fileUploadMAX[infoid]['mc']) {
        var o = $(fileUploadMAX[infoid]['id']); if (o != undefined) $HIDEB('ifAttachAdd' + fileUploadMAX[infoid]['id']);
    }
    objDisplay.style.height = (32 * fileUploadMAX[infoid]['nc']) + 'px';
    objDisplay.parentNode.style.height = (32 * fileUploadMAX[infoid]['nc']) + 24 + 'px';
}

//첨부파일 삭제, UI에서만 제거
function DeleteAttach(infoid, fileid, key, filename) {
    var objDisplay = document.getElementById(infoid);
    var objAttach = document.getElementById(fileid);
    var objAttachInfo = document.getElementById("atttabl" + filename);

    if (objAttach != undefined) {
        objAttach.value = objAttach.value.replace(key, '');
        if (objAttach.value < 2) objAttach.value = '';

        objAttachInfo.style.height = '0px';
        objAttachInfo.style.display = 'none';

        fileUploadMAX[infoid]['nc']--;
        if (fileUploadMAX[infoid]['nc'] < 0) fileUploadMAX[infoid]['nc'] = 0;
        if (fileUploadMAX[infoid]['nc'] < fileUploadMAX[infoid]['mc']) {
            var o = $(fileUploadMAX[infoid]['id']); if (o != undefined) $SHOWB('ifAttachAdd' + fileUploadMAX[infoid]['id']);
        }
    }
    objDisplay.style.height = (32 * fileUploadMAX[infoid]['nc']) + 'px';
    objDisplay.parentNode.style.height = (32 * fileUploadMAX[infoid]['nc']) + 24 + 'px';
}

//첨부파일 목록 키 정보 얻기(서버에 정보 넘길 때 사용)
function GetAttachKeys(uiid) {
    var fileinfo = document.getElementById("hidFiles" + uiid);

    if (fileinfo != null || fileinfo != undefined || fileinfo.value.length > 0) {
        return fileinfo.value;
    }

    return '';
}
