function getHttprequest(URL) {
    var xmlhttp = null;

    if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.open('GET', URL,false);

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState==4 && xmlhttp.status == 200 && xmlhttp.statusText=='OK') {
            responseText = xmlhttp.responseText;
        }
    };
    xmlhttp.send('');
    return responseText = xmlhttp.responseText;
}


/**
 * setTimeout 으로 이동되면 스크롤을 Event로 핸들링 처리함
 * made by ul
 */

var aMoveNodes      = [];
var pageHeight      = 0;
var movePosY        = 0;

function set_move_banner()
{
	var isNode	= false;
	var aMoveNodeIds = [];
	aMoveNodeIds[aMoveNodeIds.length] = document.getElementById('r_scroll_area') ? 'r_scroll_area' : 'scroll_banner_r';
	aMoveNodeIds[aMoveNodeIds.length] = document.getElementById('l_scroll_area') ? 'l_scroll_area' : 'scroll_banner_l';

	for(var i=0; i<aMoveNodeIds.length; i++) {
		var node = document.getElementById(aMoveNodeIds[i]);

		if(node) {
			aMoveNodes.push(node);
			isNode = true;
		}
	}

	if(!isNode) return false;

	pageHeight = document.body.scrollHeight;
	_setScroll();

	window.onscroll = _setScroll;

	function _setScroll()
	{
		var top_y = document.body.scrollTop;
		var isMove = false;

		for(var i=0; i<aMoveNodes.length; i++) {

			if(document.body.scrollHeight <= pageHeight) {
				aMoveNodes[i].style.marginTop = top_y+'px';
				movePosY = top_y; isMove = true;
			}

			if(isMove == false && movePosY > top_y) {
				aMoveNodes[i].style.marginTop = top_y+'px';
			}
		}
	}
}

function move_banner()
{
}

// 최근본상품 스크립트 시작 jsyoon 05/11/21
var timerID = null;
var np_active;
var np_speed;
var dspcnt;

function ScrollUp(){
	if(parseInt(obj[np_active].style.top) == 0){
		alert('최근 본 첫상품입니다.');
		return;
	}
	if(document.getElementById){
		if(parseInt(obj[np_active].style.top) < 0){
			obj[np_active].style.top = parseInt(obj[np_active].style.top) + np_speed + "px";
		}
		//timerID = setTimeout("ScrollUp("+np_speed+")",30);
	}
}

function ScrollDown(){
	if(document.getElementById){
		var remain_height = parseInt(obj[np_active].style.height) + (parseInt(obj[np_active].style.top));
		if(remain_height <= (dspcnt * np_speed)){
			alert('최근 본 마지막상품입니다.');
			return;
		}
		if(parseInt(obj[np_active].style.top) > document.getElementById('cont').offsetHeight - obj[np_active].offsetHeight){
			obj[np_active].style.top = parseInt(obj[np_active].style.top) - np_speed + "px";
		}
		//timerID = setTimeout("ScrollDown("+np_speed+")",30);
	}
}

function ScrollStop(){
	if(document.getElementById){
		clearTimeout(timerID);
	}
}

function ScrollPageInit(rowcnt, rowlimit) {
	var tbl_row =  document.getElementById("tbl_row0");
	var inner_width = 0;
	var inner_height = 0;
	var cont_obj;
	var tmp_obj;
	dspcnt = rowlimit;
	np_active = 0;
	if(tbl_row == undefined || rowcnt <= 0)
		return;
	else {
		//inner_width = parseInt(tbl_row.width);
		// 타이틀이미지의 크기를 불러와서 리스트 테이블 넓이로설정
		var rview_timg = new Image();
		rview_timg.src = document.getElementById("rviewpdt_img").src;
		inner_width = rview_timg.width;
		for(var i=0; i < rowcnt; i++){
			tmp_obj = document.getElementById("tbl_row" + i);
			if (tmp_obj != null) tmp_obj.width = inner_width;
		}
		//리스트 테이블 높이설정
		inner_height = parseInt(tbl_row.height);
		if(inner_width <= 0 || inner_height <= 0)
			return;
		np_speed = inner_height;
		cont_obj = document.getElementById("cont");
		cont_obj.style.width = inner_width;
		cont_obj.style.height = (rowcnt > rowlimit ? (inner_height * rowlimit + 1) : (inner_height * rowcnt + 1)) + 'px';
	}
	if(document.getElementById){
	var	obj = document.getElementById("cont").getElementsByTagName("DIV");
		obj['inner_row'].style.visibility = "visible";
		obj['inner_line'].style.visibility = "visible";
		obj['inner_row'].style.height = (inner_height * rowcnt) + 'px';
		obj['inner_row'].style.width = inner_width + 'px';
		obj['inner_row'].style.top = 0;
	}
	if(document.addEventListener){
		for(i=0;i<document.getElementsByTagName('a').length;i++){
			document.getElementsByTagName('a')[i].style.position = "relative";
		}
	}
    return obj;
}
// 최근본상품 끝

function check_gonggu()
{
	alert('공동구매 기간이 아닙니다');
}

function poll_form_submit( form )
{

        select_no_length = form.select_no.length;
    is_checked = false;

        for( i = 0; i < select_no_length; i++ )
        {
        if( form.select_no[i].checked )
        {
            is_checked = true;
            break;
        }
        }
        
    if( !is_checked )
    {
        alert( '설문항목을 선택해주세요.' );
        return false;
    }

    // 설문 가능여부 체크.20100618
    if (document.getElementById('poll_status') && document.getElementById('poll_status').value != 'T') {
        alert('설문조사 기간이 아닙니다.');
        return false;
    }
    return true;
}

function sMmove( sLink )
{
    document.location.href = 'http://' + sLink;
    oWin.close();
}

function getCookie(name) {
    var nameOfCookie = name + "=";
    var x = 0;

    while (x <= document.cookie.length) {
        var y = x + nameOfCookie.length;
        if (document.cookie.substring(x, y) == nameOfCookie) {
            if ((endOfCookie=document.cookie.indexOf(";", y)) == -1) {
                endOfCookie = document.cookie.length;
            }
            return unescape(document.cookie.substring(y, endOfCookie));
        }
        x = document.cookie.indexOf(" ", x) + 1;
        if (x == 0) {
            break;
        }
    }
    return "";
}

function DeleteRecentView() {
    var count = 0;
    var cnt = document.CheckBox.length;
    var obj = document.CheckBox;

    if(cnt == undefined){
        cnt = 1; //언디파인드이면 1을 강제로 주고
    }

    for (var i=0;i < cnt;i++){
        if (obj[i].checked==true){
            var url = '/Front/?url=DeleteRecentView&prdNum=' + obj[i].value;
            getHttprequest(url);
            count++;
        }
    }

    if(count == 0) {
        alert('하나는 선택하세요');
        return ;
    }

    //createHiddenIframe();
    //document.getElementById('hidden_ifr').src = '/Front/?url=DeleteRecentView&sPrdInfo=' + sPrdInfo;

    document.location.reload();
}

function notice_popup(is_popup_check, mp_width, mp_height, mp_left_p, mp_top_p, mp_scrollbars)
{
	if (getCookie("mp_is_popup") == "") {
		mp_option = 'status:false;';
		mp_option += 'dialogWidth: ' + mp_width + 'px;';
		mp_option += 'dialogHeight: ' + mp_height + 'px;';
		mp_option += 'help:no; dialogLeft:' + mp_left_p + 'px;';
		mp_option += 'dialogTop:' + mp_top_p + ';';
		mp_option += 'status:no;scroll:' + mp_scrollbars + ';';

		url = '/admin/php/d/popup_r.php';
		url_name = 'echosting_shop_pop';

		var oWin = showModelessDialog( url, window, mp_option );
	}
}

function echosting_js_init()
{
	// 좌,우측 움직이는 배너
	set_move_banner();
	//window.setInterval( "set_move_banner()", scroll_time );
	//window.setTimeout( "set_move_banner()", scroll_time );
	loginForm();
	ecFrameCheck();
}
if( window.attachEvent )  // IE의 경우
    window.attachEvent( "onload", echosting_js_init);
else  // IE가 아닌 경우.
    window.addEventListener( "load", echosting_js_init, false );




function ecFrameCheck()
{
    var aCookie = document.cookie.split(';');
    for(var i=0; i<aCookie.length; i++) {
        if(aCookie[i].indexOf('ecframe_set') >= 0) {
            var aFrameInfo = aCookie[i].split('=');
            if(opener) {
                return;
            }
            if(parent == self && aFrameInfo[1] == 'F') {
                ec_setCookie('ecframe_set', '');
                window.location.href='/Front/?return_url='+escape(new String(document.location.href));
            }
        }
    }
}

function ec_setCookie(name, value, expires, path, domain, secure)
{
    path = '/';
    expires = 0;
    if(expires != 0) {
        var dd = new Date(expires * 1000);
        var expst = '; expires='+dd.toGMTString();
    } else expst = '';

    var cookstr = name + '=' + value +
        ((expires == 0) ? '' : (expst)) +
        ((path == null) ? '' : ('; path=' + path)) +
        ((domain == null) ? '' : ('; domain=' + domain)) +
        ((secure == true) ? '; secure' : '');
    document.cookie = cookstr;
}


var login_mallid        = '';
var login_host          = '';
var login_sessionid     = '';
function loginForm()
{
    var nodes = document.getElementsByTagName('form');

    var sslUrl = getCookie('ssl_url');

    for(var i=0; i < nodes.length; i++)
    {
        if(nodes[i].name != 'login_f' && nodes[i].name != 'login_frm') continue;

        if (nodes[i].name == 'login_f') {
            if (document.location.href.toString().indexOf('url=Basketlogin') > 0) {
                document.login_f.redirect_url.value = '/Front/Order/?url=Address';
            }
        }

        var inpNodes = nodes[i].getElementsByTagName('input');
        for(var j=0; j<inpNodes.length; j++) {
            if(inpNodes[j].getAttribute('name') == 'is_ssl') {
                inpNodes[j].checked = true;
                
                // post 방식으로 변경한다.
                try {
                    createHiddenInput(nodes[i], 'secure', 'login');
                    createHiddenInput(nodes[i], 'host', new String(document.domain));
                } catch (e) {}
            }
        }

        nodes[i].onsubmit = function() {
            /*alert(this.action);
            return false;*/
            createHiddenIframe();

            var nodes = this.getElementsByTagName('input');
            for(var i=0; i<nodes.length; i++) {
                if(nodes[i].name == 'redirect_url') {
                    nodes[i].value = escape(nodes[i].value);
                }
            }

            this.target = 'hidden_ifr';
            
            try {
                if (this["is_ssl"].checked) {
                    if(AuthSSL_encode(this, ["id", "passwd"]) == true)
                        return false;
                }
            } catch (e) {}

            return true;
        };
    }
}

// form 에 input hidden 값 추가
// by hmkim on 2010-07-02
function createHiddenInput(objFrm, name, value)
{
    var node = document.createElement('input');
    node.type = 'hidden';
    node.id = name;
    node.name = name;
    node.value = value;
    objFrm.appendChild(node);
}

function createHiddenIframe() {
    if(!document.getElementById('hidden_div')) {
        var node = document.createElement('div');
        node.id = 'hidden_div';
        node.innerHTML = '<iframe src="about:blank" name="hidden_ifr" id="hidden_ifr" width="0" height="0"></iframe>';
        node.style.display = 'none';
        document.body.appendChild(node);
    }
}

// 한글 크기를 체크하는 함수 by jsyoon
function str_size_check(str){
        var strlen = str.length;
        var bsize = 0;
        for(i=0; i<strlen; i++){
                chr =   str.charAt(i);
                // 한글이면 2를 더한다.
                if (escape(chr).length > 4)
                {
                        bsize += 2;
                }
                // 그밖의 경우는 1을 더한다.
                else
                {
                        bsize++;
                }
        }
        return bsize;
}

function check_byte(frm, maxsize, msg){
        var txtval  = frm.value;
        var bsize = 0;
        bsize = str_size_check(txtval);
        if(bsize > maxsize){
                alert(msg);
                return false;
        } else {
        return true;
    }
}

// 입력폼의 문자가 숫자인지를 체크 by jsyoon
function checkDigit(inputval)
{
        inputstr = inputval.toString();
        for ( var i=0; i < inputstr.length; i++)
        {
                var onechar = inputstr.charAt(i);
                if ((onechar < "0" || onechar > "9"))
                {
                        return false;
                }
        }
        return true;
}
// 자바스크립트 number_format jsyoon
function number_format(str)
{
    str+='';

    var objRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');

    while(objRegExp.test(str))
    {
        str = str.replace(objRegExp, '$1,$2');
    }

    return str;
}

function set_ssl_login( frm )
{
    void(0);
}




// object관련 script 파일
function set_Embed()
{
    var option = [];
	var src = '';
	var width = 0;
	var height = 0;
	var getType = '';

	this.init = function(src,width,height,getType) {
		this.src     = src;
		this.width    = width;
		this.height   = height;
		this.getType  = getType;
		this.parameter('movie', src);
	};

    this.parameter = function(key, value){
		option[option.length] = key+'|'+value;
    };

	this.show = function(getType) {
		var objectHtml = [];
		objectHtml.push('<object  classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="'+this.width+'" height="'+this.height+'" >');

		for(var i=0; i<option.length; i++) {
			var opt = option[i].split('|');
			objectHtml.push('<param name="'+opt[0]+'" value="'+opt[1]+'" />');
		}
		objectHtml.push('<param name="allowScriptAccess" value="always" />');
		objectHtml.push('<embed src="'+this.src+'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="transparent" allowScriptAccess="always" width="'+this.width+'" height="'+this.height+'" name="objectTag" allowScriptAccess="always" swLiveConnect="true"></embed>');
		objectHtml.push('</object>');
		document.write(objectHtml.join(''));
	};
}

//전자보증보험 증권 내용 연결 팝업스크립트
function usafe_print(asMallId, asOrderId)
{
    var iXpos;
    var iYpos;

    iXPos = (screen.width  - 700) / 2;
    iYpos = (screen.height - 600) / 2;
    asOrderId = asOrderId.replace(/-/gi, '');
        url = "https://gateway.usafe.co.kr/esafe/InsuranceView.asp?mall_id="+asMallId+"&order_id="+asOrderId;
        winname = "uclick_win" ;
        //option = "toolbar=no location=no scrollbars=yes width=650 height=537 left="+iXpos+",top="+iYpos ;
        option = "toolbar=no location=no scrollbars=yes width=650 height=537" ;
        opener = window.open( url, winname, option ) ;
}
// 마우스 오른쪽클릭 사용금지
function disableMouseRightButton()
{
    if ((event.button==2) ||  (event.button==3))
    {
        alert("무단도용방지를 위하여 마우스 오른쪽\n\n 버튼은 사용하실 수 없습니다.");
        return false;
    }
}
//컨트롤키 및 펑션키 금지
function disableKeys()
{
    if((event.ctrlKey == true && (event.keyCode == 78 || event.keyCode == 82)) ||
        (event.keyCode >= 112 && event.keyCode <= 123))
    {
        event.keyCode = 0;
        event.cancelBubble = true;
        event.returnValue = false;
    }
}

/**
    * 사용자 정의 함수
    *
    * @author 이경란<krlee2@simplexi.com>
    * @date 2008-05-28
    * sample
    * getLog('/front/php/b/board_list.php','myshop','c_1','')
**/
function getLog(sURL,path1,path2,path3)
{

    if (path1 == null) {
        path1 = '';
    }
    if (path2 == null) {
        path2 = '';
    }
    if (path3 == null) {
        path3 = '';
    }

    if (sURL == '' && path1 == '' && path2 == '' && path3 == '' ){
        alert('sURL또는 path1또는 path2또는 path3를 입력하셔야합니다');
    }else if (sURL == ''){
        alert('sURL을 입력하셔야합니다');
    }else   if (path1 == ''&& path2 == '' && path3 == ''){
        alert('path1또는 path2를 입력하셔야합니다');
    }else if (sURL != '' && ( path1 != '' || path2 != '' || path3 != '' ) ){
        var path1_size = str_size_check(path1);
        var path2_size = str_size_check(path2);
        var path3_size = str_size_check(path3);
        var sURL_size = str_size_check(sURL);
        if(path1_size > 255) {
            alert("첫번째 인자가 너무 깁니다.");
            return;
        }
        if(path2_size > 255) {
            alert("두번째 인자가 너무 깁니다.");
            return;
        }
        if(path3_size > 255) {
            alert("세번째 인자가 너무 깁니다.");
            return;
        }
        if(sURL_size > 255) {
            alert("전달 URL의 길이가 너무 깁니다.");
            return;
        }
        location.href = "/front/php/get_log.php?sCliMode=Evnt&sURL="+sURL+"&path1="+path1+"&path2="+path2+"&path3="+path3;
    }
}


/**
 * 출석체크
 * param1 : 이벤트번호
 */
function AttendJoin(param1) {
    location.replace('/Front/Myshop/?url=setAttendEvent&param1='+param1);
}

function strchk(str, obj)
{
    if(!checkDigit(str)) {
        alert('숫자만 입력할 수 있습니다.');
        obj.value='';
        return false;
    }
}

function priceFormat (iNumber, sContryCode, numFlag){

    //나라별 소수점 정보
    var aDecimals = {
        'KR' : 0,
        'US' : 2,
        'JP' : 0,
        'CN' : 2,
        'EU' : 0,
        'KE' : 0,
        'NO' : 0
    };
    if (!numFlag) {
        numFlag = '';
    }
    return this.numberFormat(parseFloat(iNumber), aDecimals[sContryCode], '.', numFlag);
}

function numberFormat( number, decimals, dec_point, thousands_sep ) {
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? '.' : dec_point;
    var t = thousands_sep == undefined ? ',' : thousands_sep, s = n < 0 ? '-' : '';
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + '', j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
}

function setPayLocation(sValue, pg_disp_type, sContryCode) {
    if (!sContryCode) sContryCode = 'KR';
    if (!pg_disp_type) pg_disp_type = 'S';
    var aData = {"KR":{"1":"\uffe6","2":"\uc6d0"},"JP":{"1":"\uffe5","2":""},"US":{"1":"\uff04","2":""},"CN":{"1":"","2":"\u5143"},"EU":{"1":"\u20ac","2":""},"KE":{"1":"","2":"won"},"NO":{"1":"","2":""}};
    var aResult = aData[sContryCode];

    if (sContryCode == 'KR') {
        if (pg_disp_type == 'S') {
            aResult['2'] = '';
        } else if (pg_disp_type == 'D') {
            aResult['1'] = '';
        }
    }
    return aResult['1'] + sValue + aResult['2'];
}

function changeLeftMenu()
{
    if (document.getElementById('leftOpenMenu').style.display == 'none') {
        document.getElementById('leftOpenMenu').style.display = 'block';
        document.getElementById('leftCloseMenu').style.display = 'none';
    } else {
        document.getElementById('leftOpenMenu').style.display = 'none';
        document.getElementById('leftCloseMenu').style.display = 'block';
    }
}

function chkAttend(idx)
{
    if(!idx) {
        alert('선택 된 출석체크 이벤트가 없습니다.');
    } else {
        location.replace('/Front/Myshop/?url=setAttendNewCustom&iAttendIdx=' + idx);
    }
}

function setResultBanner(oj2)
{
    eval("var res = " + oj2.responseText);

    document.search_form_b.keyword.value = res.bContents;
    document.search_form_b.bn_type.value = res.bType;
    document.search_form_b.bn_prt_no.value = res.bPrdNo;
    document.search_form_b.bn_cate_no.value = res.bCateNo;
    document.search_form_b.bn_keyword.value = res.bKeyword;
    document.search_form_b.bn_url.value = res.bUrl;
}

function setSearchBanner()
{
    sendRequest(setResultBanner, '','POST', '/Front/Mall/?url=Searchbanner', false, false);
    return false;
}

function setClear()
{
    document.search_form_b.keyword.value = '';
    document.search_form_b.bn_type.value = '';
}

/*
 * EC.DRAG 가져옴
 *  
 */
var Drag={

        "obj":null,

        "init":function(a, aRoot, ee){
                if (!ee) {      //ee == null 을 변경 2008-05-13 박준영
                    a.onmousedown=Drag.start;
                }
                a.root = aRoot;
                if(isNaN(parseInt(a.root.style.left))) { a.root.style.left="0px"; }
                if(isNaN(parseInt(a.root.style.top))) { a.root.style.top="0px"; }
                a.root.onDragStart = new Function();
                a.root.onDragEnd = new Function();
                a.root.onDrag = new Function();

                if (!!ee) {     //ee != null 을 변경 2008-05-13 박준영
                    var b = Drag.obj = a;
                    ee = Drag.fixE(ee);
                    var c = parseInt(b.root.style.top);
                    var d = parseInt(b.root.style.left);
                    b.root.onDragStart(d,c,ee.clientX,ee.clientY);
                    b.lastMouseX = ee.clientX;
                    b.lastMouseY = ee.clientY;
                    document.onmousemove    = Drag.drag;
                    document.onmouseup      = Drag.end;
                }

            },


        // 드레그 스타트 시에... cron 생성 처리
        "start":function(a){
                
                var b=Drag.obj=this;
                a=Drag.fixE(a);

                var c = parseInt(b.root.style.top);
                var d = parseInt(b.root.style.left);

                b.root.onDragStart(d,c,a.clientX,a.clientY);

                b.lastMouseX = a.clientX;
                b.lastMouseY = a.clientY;

                document.onmousemove    = Drag.drag;
                document.onmouseup      = Drag.end;
                return false;
            },


        "drag":function(a){
                a = Drag.fixE(a);
                var b = Drag.obj;
                var c = a.clientY;
                var d = a.clientX;
                var e = parseInt(b.root.style.top);
                var f = parseInt(b.root.style.left);
                var h,g;
                h = f + d - b.lastMouseX;
                g = e + c - b.lastMouseY;
                b.root.style.left   = h + "px";
                b.root.style.top    = g + "px";
                b.lastMouseX        = d;
                b.lastMouseY        = c;
                b.root.onDrag(h, g, a.clientX, a.clientY);          
                return false;
            },


        "end":function(){
                document.onmousemove    = null;
                document.onmouseup      = null;
                Drag.obj.root.onDragEnd(parseInt(Drag.obj.root.style.left),parseInt(Drag.obj.root.style.top));          
                Drag.obj = null;
            },


        "fixE":function(a){
                if(typeof a == "undefined") { a=window.event; }
                if(typeof a.layerX == "undefined") { a.layerX=a.offsetX; }
                if(typeof a.layerY == "undefined") { a.layerY=a.offsetY; }
                return a;
            }
};


// 상품요약정보 (툴팀제공) : 이경란(2009-11-30)
var config12 = {'className':'jsTooltip'};
var config3  = {'className':'jsTooltip2'};

var jsTooltip =  function(evt, target, str, configSetting) 
{
    //==체크
    if(str==null || str==''){return false;}
    var config = {'gapLeft':5 ,'gapTop':5 , 'className':'jsTooltip','style':{} };
    if (configSetting) {
        for (x in configSetting) {
            if(config[x] != undefined) {
                config[x] = configSetting[x];
            }
        }
    }
    //== 변수값 설정
    this.target = target
    this.str = str
    this.gapLeft = config['gapLeft'];
    this.gapTop = config['gapTop'];
    divTooltip = document.createElement('div');
    divTooltip.className = config['className'];
    divTooltip.innerHTML = this.str;
    //divTooltip.appendChild(document.createTextNode(this.str));
    this.target.divTooltip = divTooltip;
    //== 스타일 설정
    if (config['style'] != null) {
            for (x in config['style']) {
            divTooltip.style[x] = config['style'][x];
        }
   }
    divTooltip.style.display = 'none';
    divTooltip.style.left = 0;
    divTooltip.style.right = 0;
    divTooltip.style.position = 'absolute';

    if (divTooltip.className == 'jsTooltip') {
        divTooltipImg = document.getElementById('tooltip_basic').cloneNode();
        divTooltipImg.style.display = 'none';
        divTooltipImg.style.left = 0;
        divTooltipImg.style.right = 0;
        divTooltipImg.style.position = 'absolute';
        document.body.appendChild(divTooltipImg);
        this.target.divTooltipImg = divTooltipImg;
    }

    document.body.appendChild(divTooltip);
    var thisC = this;
    this.target.onmouseover = function(evt){ thisC.show(evt,thisC.target); }
    this.target.onmousemove = function(evt){ thisC.show(evt,thisC.target); }
    this.target.onmouseout = function(evt){ thisC.hide(evt,thisC.target); }
    if (evt && evt.type == 'mouseover') {
        thisC.show(evt,thisC.target);
    }
}

jsTooltip.prototype.show = function(evt,target)
{
       if(window.event){ evt = window.event ;}
       if(target.divTooltip){
               var scrollLeft = Math.max(document.documentElement.scrollLeft,document.body.scrollLeft);
               var scrollTop = Math.max(document.documentElement.scrollTop,document.body.scrollTop);
               var scrollWdith = Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);
               var scrollHeight = Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);

               target.divTooltip.style.display = 'block';
               var divRight = evt.clientX + target.divTooltip.offsetWidth;
               var divBottom = target.divTooltip.offsetTop+target.divTooltip.offsetHeight;
               var x = evt.clientX+this.gapLeft+scrollLeft;
               if (divTooltip.className == 'jsTooltip') {
                       var y = evt.clientY+this.gapTop+scrollTop-203;
               }else {
                       var y = evt.clientY+this.gapTop+scrollTop;
               }
               //var y = evt.clientY+this.gapTop+scrollTop-203;

               if(divRight + scrollLeft + this.gapLeft + 20 >= scrollWdith){
                       x = (scrollWdith - target.divTooltip.offsetWidth - 10 );

               }

               target.divTooltip.style.left = x+'px';
               target.divTooltip.style.top = y+'px';

               if (divTooltip.className == 'jsTooltip') {
                   target.divTooltipImg.style.left = x+'px';
                   target.divTooltipImg.style.top = y+'px';
                   target.divTooltipImg.style.display = 'block';
                  }
       }
}

jsTooltip.prototype.hide = function(evt,target)
{
       if(target.divTooltip){
               target.divTooltip.style.display = 'none';
               if (divTooltip.className == 'jsTooltip') {
                    target.divTooltipImg.style.display = 'none';
                }
       }
}

// IE6 png 처리
function setPng24(obj)
{
    obj.width=obj.height=1;
    obj.className=obj.className.replace(/\bpng24\b/i,'');
    obj.style.filter =
    "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+ obj.src +"',sizingMethod='image');"
    obj.src=''; 
    return '';
}

// 방문 카테고리 div표시
function popUpVisitCate()
{
    if (document.getElementById('div_visitCategory')) {
        var divObj = document.getElementById('div_visitCategory');
        // 이미 열려 있을경우에는 다시 열지 않습니다.
        divObj.style.top  = document.body.clientHeight/2 - divObj.clientHeight/2 + document.body.scrollTop;
        divObj.style.left = document.body.clientWidth /2 - divObj.clientWidth /2 + document.body.scrollLeft;
        return false;
    }
    
    if (sendRequest) {
        var divObj = document.createElement("div");
        divObj.id = 'div_visitCategory';
        divObj.style.position = 'absolute';
        divObj.style.display  = 'none';
        document.body.appendChild(divObj);
        
        sendRequest(json_visit_cate, '&url=Visitcate','POST', '/Front/Myshop/', true, true);
    } else {
        alert('ajax 라이브러리가 로드되지 않았습니다. 관리자에게 문의하여 주세요.');
    }
}

// 방문 카테고리 div를 닫습니다.
function closeVisitCate()
{
    var divObj = document.getElementById('div_visitCategory');
    if (divObj) {
        divObj.parentElement.removeChild(divObj);
    }
}

// 방문 카테고리를 표시합니다.
function json_visit_cate(oj) {
    try {
        var divObj = document.getElementById('div_visitCategory');
        divObj.innerHTML = oj.responseText;
        divObj.style.display = 'block';
        divObj.style.top  = document.body.clientHeight/2 - divObj.clientHeight/2 + document.body.scrollTop;
        divObj.style.left = document.body.clientWidth /2 - divObj.clientWidth /2 + document.body.scrollLeft;
    } catch(e) {}
}

// 상품목록내에서 옵션미리보기
var bIsParent = false;
var bIsChild = false;
function showOptionView(sPrdCode, oBtnObj, iWidth, sEventName)
{
    try {
        var oObj = document.getElementById('cate_opt_previewLayer');
        var bIE = new RegExp(/MSIE/).test(navigator.userAgent); // MS Internet Explorer        
        if (bIE) {
            var XY = getAbsPosition();
        } else {
            if (oObj != undefined || oObj != null) {
                var oParent = oObj.parentNode;
                oParent.removeChild(oObj);
                oObj = null;
            }
        }

        if (iWidth == undefined) {
            iWidth = 200;
        }

        var bDone = false;
        var bLive = false;
        if (oObj == undefined || oObj == null) {
            bDone = true;
        } else {
            //var oParent = oObj.parentNode;
            //oParent.removeChild(oObj);
            oObj.style.display = 'block';
            bDone = true;
            bLive = true;
        }
        
        if(bDone == true) {
            var iItemCnt = getHttprequest('/Front/Product/?url=Optionview&product_no='+sPrdCode+'&mode=item_cnt');
            var iItemHeight = (18 * iItemCnt) + 8 + 20;
            //레이어 생성
            if (bLive == true) {
                if (bIE) {
                    oObj.style.left = document.body.scrollLeft + XY.x;
                    oObj.style.top = document.body.scrollTop + XY.y + 17;
                }
                oObj.style.display = 'block';
                document.getElementById('cate_opt_preview').style.height = iItemHeight + 'px';                
                document.getElementById('cate_opt_preview').src = '/Front/Product/?url=Optionview&product_no='+sPrdCode;
            } else {
                var oViewLayer = document.createElement('div');
                oViewLayer.setAttribute('id', 'cate_opt_previewLayer');
                oViewLayer.style.position = 'absolute';
                oViewLayer.style.zindex = '1000';
                oViewLayer.style.width = iWidth + 'px';
                oViewLayer.style.display = 'block';
                oViewLayer.style.height = iItemHeight + 'px';

                //iframe 생성
                var oViewIframe = document.createElement('iframe');
                oViewIframe.setAttribute('id', 'cate_opt_preview');
                oViewIframe.setAttribute('frameBorder', '0');
                oViewIframe.setAttribute('border', '0');
                oViewIframe.setAttribute('scrolling', 'no');
                oViewIframe.style.width = iWidth + 'px';
                oViewIframe.style.border = '1px solid #ccc';
                oViewIframe.style.height = iItemHeight + 'px';
                
                if (sEventName == 'onmouseover') {
                    oViewIframe.onmouseover = function() {
                        parent.showOptionLayer('child');
                    }
                    oViewIframe.onmouseout = function() {
                        parent.showOptionLayer('child');
                    }
                }

                oViewIframe.src = '/Front/Product/?url=Optionview&product_no='+sPrdCode;
                if (bIE) {
                    oViewLayer.style.left = document.body.scrollLeft + XY.x;
                    oViewLayer.style.top = document.body.scrollTop + XY.y + 17;
                    document.getElementsByTagName("body")[0].appendChild(oViewLayer);
                } else {
                    oViewLayer.style.marginTop = -2;
                    oBtnObj.parentNode.appendChild(oViewLayer);
                }
                oViewLayer.appendChild(oViewIframe);
            }
            bIsParent = true;
        }
    } catch(e) {
    }
}

// 옵션미리보기 layer show/hide
function showOptionLayer(sType)
{
    var oLayerObj = document.getElementById('cate_opt_previewLayer');
    if (oLayerObj != undefined) {
        if(sType == 'parent') {
            if(oLayerObj.style.display == 'none') {
                oLayerObj.style.display = 'block';
                bIsParent = true;
            } else {
                if(bIsChild == false) {
                    oLayerObj.style.display = 'none';
                    bIsParent = false;
                }
            }
        } else {
            if(oLayerObj.style.display == 'none') {
                oLayerObj.style.display = 'block';
                bIsChild = true;
            } else {
                if(bIsParent == false) {
                    oLayerObj.style.display = 'none';
                    bIsChild = false;
                }
            }
        }
    }
}

// 옵션미리보기창 위치
function getAbsPosition() 
{
    var top = 0, left = 0;
    e = window.event;
    var myTarget = e.currentTarget;
    if (!myTarget) {
        myTarget = e.srcElement;   
    } else if (myTarget == "undefined") {
        myTarget = e.srcElement;
    }
    while(myTarget!= document.body) {
        top += myTarget.offsetTop;
        left += myTarget.offsetLeft;
        myTarget = myTarget.offsetParent;
    }
    return {x: left-document.body.scrollLeft, y: top-document.body.scrollTop};
}

// 옵션미리보기창 윈도우조절
function resizeFrame() {
    /*try {
        window.resizeTo(document.body.scrollWidth, document.body.scrollHeight);
    } catch (e) {
        errCnt++;
        if(errCnt > 10) return;
        setTimeout("resizeFrame();", 500);
    }*/
}

///////////////////////////////////////////////
//여기서 부터 인기상품 롤링 스크립트///////////
///////////////////////////////////////////////
var init_val = false;
var msgs_keyword = new Array();
var chkOver = true;
var MOver = false;
var step = 1; 
var layerHeight = 30; 
var interval =17; 
var delay = 7000;

function pauseRolling() {   MOver = true; startList();}
function resumeRolling() {MOver = false; stopList();}
function stopRolling() {chkOver = false;}
function startRolling() {
  if (MOver == true) {    
      setTimeout("startRolling()", delay);
  } else {    
      chkOver = true; 
      moveRolling();
  }
}
function startList()
{
  document.getElementById('real_favor_product_list').style.display = "inline";
}
function stopList()
{
  document.getElementById('real_favor_product_list').style.display = 'none';
}
function init_live_hot_item(sSetPrdInfo) {
  var jsonPrdInfo = eval("(" + sSetPrdInfo + ")");
  var sPrdCnt = jsonPrdInfo.length;
  var arrPremiumBg_minihp = new Array();
  for (var i=0 ; i<sPrdCnt; i++) {
      arrPremiumBg_minihp[i] = jsonPrdInfo[i];
  }

  var classNm = "";
  var nextj = 0;

      for(var j=0; j<sPrdCnt;j++){
          nextj = j+1;    

          msgs_keyword[j]="<li id='msg_keyword_"+j+"'  style='list-style:none;margin:0; padding:0;position:absolute; clear:both; float:left; '>";
          msgs_keyword[j]+=arrPremiumBg_minihp[j];
          msgs_keyword[j]+="</li>";
      }

  //var ran = Math.round(Math.random()*(msgs_keyword.length-1));
  var ran = 0;
  for (i=0;i < msgs_keyword.length;i++)   {
          document.getElementById('rankArea').innerHTML += msgs_keyword[i];
          Obj = eval("document.getElementById('msg_keyword_"+i+"')");

          if (i-ran < 0){
              Obj.style.top = (i-ran) * layerHeight + msgs_keyword.length*layerHeight + "px";
          }else{
              Obj.style.top = (i-ran) * layerHeight+"px";
          }
  }
  setTimeout("moveRolling()", delay);
}

function moveRolling() {
  if (!chkOver)return;

  for (i=0;i < msgs_keyword.length;i++)   {
      Obj = eval("document.getElementById('msg_keyword_"+i+"')");
      Obj.style.top = Obj.style.top.substr(0,Obj.style.top.length - 2) - step+"px";
      if (Obj.style.top.substr(0,Obj.style.top.length - 2) == -layerHeight) Obj.style.top = (msgs_keyword.length - 1) * layerHeight+"px";
      if(Obj.style.top == '0px'){
          if (!init_val)

          stopRolling(); setTimeout("startRolling()", delay); 
      }else{
      }
  }
  setTimeout("moveRolling()",interval);
}
////////////////////////////////////////////////////
///인기상품 롤링스크립트 끝/////////////////////////
////////////////////////////////////////////////////


/**
 * 장바구니 > 관심상품 주문 및 담기
 * @param sItemCode : 품목코드
 * @param sMode : 
 * @param sPrdCode : 상품코드
 * @param iOptionLen : 옵션길이
 * @return
 */
function add_wish_basket(sItemCode, sMode, sPrdCode, iOptionLen, iStep, sItemPrintKind)
{
    if (sMode == undefined || sMode == '') sMode = 'basket';
    var oPrdData = eval("(" + document.getElementById('sWishPrdJson').value + ")");
    var iRedirect = (sMode == 'basket') ? 0 : 1;
    var sSelectItemCode; // 옵션 선택한 품목코드 
    if (oPrdData[sItemCode].cate_code == null) oPrdData[sItemCode].cate_code = ''
    
    // 옵션선택여부확인
    if (oPrdData[sPrdCode].prd_mst.p_item_type == 2) {
        var aOption = new Array();
        if (sItemPrintKind == '1') {
            var oOptionObj = document.getElementById('option_'+iStep+'_'+sPrdCode+'0');
            var aOptionSplit = oOptionObj.value.split('::');
            for (i=0; i<aOptionSplit.length; i++) {
                var aTempOption = aOptionSplit[i].split('||');
                aOption[i] = aTempOption[1];
            }
        } else {
            for (i=0; i<oPrdData[sPrdCode].prd_mst.p_option_length; i++) {
                var oOptionObj = document.getElementById('option_'+iStep+'_'+sPrdCode+i);
                if (oOptionObj.value == '') {
                    alert('옵션을 선택해주세요');
                    oOptionObj.focus();
                    return;
                } else {
                    var aTemp = oOptionObj.value.split('||');
                    aOption[i] = aTemp[1];
                }
            }
        }
        var sSeperator = aOption.join('%2C');
        sSelectItemCode = oPrdData[sPrdCode].content[sSeperator].pi_item_code;
    } else {
        sSelectItemCode = sItemCode;
    }

    if (oPrdData[sItemCode].p_set_prd_flag == 'T') {
        if (confirm('세트상품은 옵션을 다시 선택해 주셔야 합니다.\n\n상품페이지로 이동하시겠습니까?') === true) {
            document.location.href="/Front/Product/?url=Product&product_no="+oPrdData[sItemCode].p_prd_code+"&main_cate_no="+oPrdData[sItemCode].cate_code+"&display_group=";
        }
        return;
    }

    var oForm = document.createElement('form');
    oForm.setAttribute('method', 'post');
    oForm.setAttribute('id', 'FrmWishBasket');
    oForm.setAttribute('action', '/front/php/basket.php');
    
    if (sMode == 'order') {
        var oInput = document.createElement('input');
        oInput.setAttribute('type', 'hidden');
        oInput.setAttribute('name', 'quantity');
        oInput.setAttribute('value', '1');
        oForm.appendChild(oInput);
    }
    
    var oInput = document.createElement('input');
    oInput.setAttribute('type', 'hidden');
    oInput.setAttribute('name', 'redirect_url');
    oInput.setAttribute('value', '/front/php/basket.php');
    oForm.appendChild(oInput);
    
    var oInput = document.createElement('input');
    oInput.setAttribute('type', 'hidden');
    oInput.setAttribute('name', 'redirect');
    oInput.setAttribute('value', iRedirect);
    oForm.appendChild(oInput);
    
    var oInput = document.createElement('input');
    oInput.setAttribute('type', 'hidden');
    oInput.setAttribute('name', 'wl_idx');
    oInput.setAttribute('value', oPrdData[sItemCode].wl_idx);
    oForm.appendChild(oInput);
    
    var oInput = document.createElement('input');
    oInput.setAttribute('type', 'hidden');
    oInput.setAttribute('name', 'command');
    oInput.setAttribute('value', 'add');
    oForm.appendChild(oInput);

    var oInput = document.createElement('input');
    oInput.setAttribute('type', 'hidden');
    oInput.setAttribute('name', 'product_no');
    oInput.setAttribute('value', oPrdData[sItemCode].p_prd_code);
    oForm.appendChild(oInput);
    
    var oInput = document.createElement('input');
    oInput.setAttribute('type', 'hidden');
    oInput.setAttribute('name', 'main_cate_no');
    oInput.setAttribute('value', oPrdData[sItemCode].cate_code);
    oForm.appendChild(oInput);
    
    var oInput = document.createElement('input');
    oInput.setAttribute('type', 'hidden');
    oInput.setAttribute('name', 'display_group');
    oInput.setAttribute('value', '1');
    oForm.appendChild(oInput);
        
    var oInput = document.createElement('input');
    oInput.setAttribute('type', 'hidden');
    oInput.setAttribute('name', 'prd_item_code');
    oInput.setAttribute('value', sSelectItemCode);
    oForm.appendChild(oInput);
    
    var oInput = document.createElement('input');
    oInput.setAttribute('type', 'hidden');
    oInput.setAttribute('name', 'product_price');
    oInput.setAttribute('value', oPrdData[sItemCode].p_sale_price);
    oForm.appendChild(oInput);
    
    var oInput = document.createElement('input');
    oInput.setAttribute('type', 'hidden');
    oInput.setAttribute('name', 'delv_payment');
    oInput.setAttribute('value', oPrdData[sItemCode].wl_ship_prepaid_flag);
    oForm.appendChild(oInput);
    
    
    document.getElementsByTagName('body')[0].appendChild(oForm);    
    document.getElementById('FrmWishBasket').submit();
}


/**
 * 장바구니 > 관심상품 삭제
 * @param sItemCode : 품목코드
 * @return
 */
function del_wish_basket(sItemCode)
{
    if (confirm('정말 삭제하시겠습니까?') == false) {
        return;
    }
    var oPrdData = eval("(" + document.getElementById('sWishPrdJson').value + ")");    
    
    var oForm = document.createElement('form');
    oForm.setAttribute('method', 'post');
    oForm.setAttribute('id', 'FrmWishBasket');
    oForm.setAttribute('action', '/Front/Order/?url=WishDel');
    
    var oInput = document.createElement('input');
    oInput.setAttribute('type', 'hidden');
    oInput.setAttribute('name', 'mode');
    oInput.setAttribute('value', 'idx');
    oForm.appendChild(oInput);    
    
    var oInput = document.createElement('input');
    oInput.setAttribute('type', 'hidden');
    oInput.setAttribute('name', 'wl_idx');
    oInput.setAttribute('value', oPrdData[sItemCode].wl_idx);
    oForm.appendChild(oInput);
    
    document.getElementsByTagName('body')[0].appendChild(oForm);    
    document.getElementById('FrmWishBasket').submit();
}


/**
 * 선택상품담기
 * @param basket_type : 장바구니유형
 * @return
 */
function add_interest(basket_type)
{
    try {
        var form = document.createElement('form');
        form.setAttribute('method', 'post');
        form.setAttribute('action', '/Front/Order/?url=WishAdd');
        form.setAttribute('name',   'add_interest');
        form.setAttribute('id',     'add_interest');

        var count = 0;
        var inputs = document.getElementsByTagName('input');
        for (i=0; i<inputs.length; i++) {
            if (inputs[i].name == 'chk_btn' && inputs[i].checked == true) {
                var input = document.createElement('input');
                input.setAttribute('type', 'hidden');
                input.setAttribute('name', 'prd_code[]');
                input.setAttribute('value', inputs[i].value);
                form.appendChild(input);
                count++;
            }
        }

        if (count == 0) {
           alert('상품을 선택해 주세요');
        } else {
           document.getElementsByTagName('body')[0].appendChild(form);
           document.getElementById('add_interest').submit();
        }
    } catch (e) {
        alert('디자인을 확인해 보셔야 합니다.');
    }
}


/**
 * 관심상품 옵션선택
 * @param 
 * @return
 */
 function setPrdItemCode()
 {
    
 }
 
 
 
 
 
 
 
 
 

/**
 * 폼의 Action값으로 폼 얻음
 * @param action
 * @returns form object
 */ 
function getFormByAction(action)
{
    var forms = document.getElementsByTagName("FORM");
    for(var i=0, loop=forms.length; i<loop; i++) {
        if(forms[i].action == action)
            return forms[i];
    }
    return null;
}
/**
 * load Script Files
 * 
 * @param string/array script
 */
function load_script(aURL, callback_fn)
{
    if(typeof(aURL) == "string")
        aURL = [aURL];

    var URL = aURL.shift(), callbackURL = aURL[0];
    
    var recall_fn = function() {
        var o = document.getElementById('LoadScriptContainer');
        if( o ) {
            o.parentNode.removeChild(o);
            var callback_fn = o.callback_fn;
        }

        if(aURL.length > 0)
            load_script(aURL, callback_fn);
        else if(typeof(callback_fn) == "function")
            callback_fn();
    };

    var script     = document.createElement('script');
    script.type    = 'text/javascript';
    script.id      = 'LoadScriptContainer';
    script.charset = 'utf-8';
    script.callback_fn = callback_fn;

    if(callbackURL || callback_fn) {
        if (script.readyState){  //IE
            script.onreadystatechange = function(aURL){
                if (script.readyState == "loaded" || script.readyState == "complete"){
                    script.onreadystatechange = null;
                    
                    recall_fn();
                }
            }.__bind__(this, aURL);
        } else {  //Others
            script.onload = function(aURL){
                recall_fn();
            }.__bind__(this, aURL);
        }
    }
    script.src = URL;
    document.getElementsByTagName("head")[0].appendChild(script);
}
Function.prototype.__bind__ = function() {
    for ( var i = 0, method = this , args = [] , len = arguments.length ; i < len ; i++ ) {
        args.push( arguments[ i ] );
    }
    return function() {
        return method.apply( args[0] , args.slice(1) );
    }
};

/**
 * 개인정보 암호화
 */
var AuthSSL = {
        server : null,
        key : "AuthSSLEncoded",
        Listkey : "AuthSSLListKey",
        data : [],
        getDataId : function() {
            var oDate = new Date();
            try {
                do {
                    id = Math.round(Math.random()*1000000);
                } while(typeof(AuthSSL.data[id]) !== "undefined");
                return id;
            } catch (e) {
                var oDate = new Date();
                return oDate.getTime();
            }
        }
    };

function AuthSSLScriptLoad(callback_fn, mode)
{
    // required script list
    var aURL = [];
    if(typeof(AuthSSLManager) === "undefined") {
        aURL.push("AuthSSLManager.js");
    }
    if(mode == "decode") {
        if(typeof(AuthSSLManager) === "undefined" || typeof(AuthSSLManager.unserialize) === "undefined")
            aURL.push("AuthSSLManager.plugin.js");
    }
    if(aURL.length == 0) {
        callback_fn();
        return;
    }

    // load script
    if(AuthSSL.server === null) AuthSSL.server = getHttprequest("/Admin/Api/Ssl/?url=getSslServer");
    for(var i=0,loop=aURL.length; i<loop; i++) {
        aURL[i] = AuthSSL.server+aURL[i];
    }
    load_script(aURL, callback_fn);
}
function AuthSSL_encode(oForm, aNames, after_fn)
{
    var is_ssl = true;
    
    if(is_ssl != true) {
        if(typeof(after_fn) === "function") {
            after_fn();
        }
        return false;
    }
    
    if(String(oForm.tagName).toUpperCase() !== "FORM")
        return false;

    var AuthSSL_id = AuthSSL.getDataId();
    var aEleid = [];
    
    // create AuthSSLInput
    var data = [];
    for(var i=0, loop=aNames.length; i<loop; i++) {
        var name = aNames[i];
        var target = oForm[name];
        if( ! target)   continue;

        if(typeof(target.value) != "undefined" || typeof(target.length) == "undefined")
            target = [target];

        for(var j=0,loop2=target.length; j<loop2; j++) {
            var sType = target[j].getAttribute("type");
            if(sType === "radio" || sType === "checkbox") {
                if(target[j].checked && ! target[j].disabled)
                    data.push(name+"="+target[j].value);
            } else {
                if(! target[j].disabled)
                    data.push(name+"="+target[j].value);
            }
        }
    } // end for
    var AuthSSLInput = document.createElement("INPUT");
    AuthSSLInput.type = "hidden";
    AuthSSLInput.id = "AuthSSL_" + AuthSSL_id;
    AuthSSLInput.value = data.join("&");
    document.body.appendChild(AuthSSLInput);

    // set AuthSSL.data
    AuthSSL.data[AuthSSL_id] = {"oForm":oForm, "aNames":aNames, "after_fn":after_fn};
    eval("AuthSSL.data["+AuthSSL_id+"].complete_fn = function(output){AuthSSL_encode_callback(" + AuthSSL_id + ", output);};");

    // load AuthSSLManager.weave
    var encrypt_fn = function() {
        AuthSSLManager.weave({"auth_mode": "encrypt", "aEleId": [AuthSSLInput.id], "auth_callbackName": "AuthSSL.data["+AuthSSL_id+"].complete_fn"});
    };
    new AuthSSLScriptLoad(encrypt_fn, 'encode');

    return true;
}
function AuthSSL_encode_callback(AuthSSL_id, output)
{
    var fnData = AuthSSL.data[AuthSSL_id];
    var oForm = fnData.oForm;
    var aNames = fnData.aNames;
    var after_fn = fnData.after_fn;

    // functions
    function set_disable_fn(target) {
        if(target.disabled == true)
            target.setAttribute("AuthSSL_encode_disabled", "true");
        else
            target.disabled = true;
    }
    function set_enable_fn(target) {
        if(target.getAttribute("AuthSSL_encode_disabled"))
            target.removeAttribute("AuthSSL_encode_disabled");
        else
            target.disabled = false;
    }

    // disable data
    for(var i=0, loop=aNames.length; i<loop; i++) {
        var name = aNames[i];
        var target = oForm[name];
        if( ! target)   continue;

        if(typeof(target.value) != "undefined" || typeof(target.length) == "undefined")
            target = [target];

        for(var j=0,loop2=target.length; j<loop2; j++) {
            set_disable_fn(target[j]);
        }
    } // end for

    var oSSLEle = document.createElement("INPUT");
    oSSLEle.type = "hidden";
    oSSLEle.name = AuthSSL.key;
    oSSLEle.value = output;
    oForm.appendChild(oSSLEle);

    if(typeof(after_fn) === "function") {
        after_fn(output);
    } else {
        oForm.submit();
    }

    oSSLEle.parentNode.removeChild(oSSLEle);


    // enable data
    for(var i=0, loop=aNames.length; i<loop; i++) {
        var name = aNames[i];
        var target = oForm[name];
        if( ! target)   continue;

        if(typeof(target.value) != "undefined" || typeof(target.length) == "undefined")
            target = [target];

        for(var j=0,loop2=target.length; j<loop2; j++) {
            set_enable_fn(target[j]);
        }
    } // end for

    // remove AuthSSLInput
    var AuthSSLInput = document.getElementById("AuthSSL_"+AuthSSL_id);
    document.body.removeChild(AuthSSLInput);
    AuthSSL.data[AuthSSL_id] = undefined;
}

iDecodeStatus = 1;

function AuthSSL_decode(data, callback_fn)
{
    if(typeof(data) == "string") {
        var auth_string = data;
        var type = "Element";
    } else {
        if(typeof(data[AuthSSL.key]) == "undefined") {
            if(typeof(callback_fn) == "function")
                callback_fn(data);
            return false;
        }
        var auth_string = data[AuthSSL.key];
        data[AuthSSL.key] = undefined;

        var type = typeof(data[AuthSSL.Listkey]) == "undefined" ? "Row" : "List";
    }
    
    var AuthSSL_id = AuthSSL.getDataId();

    // set AuthSSL.data
    AuthSSL.data[AuthSSL_id] = {"type":type, "data":data, "callback_fn":callback_fn};
    eval("AuthSSL.data["+AuthSSL_id+"].complete_fn = function(output){AuthSSL_decode_callback(" + AuthSSL_id + ", output);};");
    
    // load AuthSSLManager.weave
    var decrypt_fn = function() {
        AuthSSLManager.weave({"auth_mode": "decryptClient", "auth_string": auth_string, "auth_callbackName": "AuthSSL.data["+AuthSSL_id+"].complete_fn"});
    };
    new AuthSSLScriptLoad(decrypt_fn, 'decode');
}

function AuthSSL_decode_callback(AuthSSL_id, output)
{
    var output = decodeURIComponent(output);

    if( AuthSSLManager.isError(output) == true ) {
        return;
    }
    var json = AuthSSLManager.unserialize(output);

    var fnData = AuthSSL.data[AuthSSL_id];
    
    switch(fnData.type) {
        case "Element":
            for(sSort in json) {
                var data = json[sSort];
                if(sSort == "text") {
                    for(k in data) {
                        var target = document.getElementById(k);
                        if(target) {
                            target.innerHTML = data[k] ? data[k] : "";
                        }
                    } // end for
                    
                } else {
                    var form = eval("document."+sSort.substr(5));
                    for(k in data) {
                        var target = form[k];
                        if(target) {
                            target.value = data[k] ? data[k] : "";
                            if (target.value == '') {
                                if (target.name == 'email2') {
                                    target.value = 'etc';
                                }
                            }
                        }
                    } // end for
                }
            } // end for
            break;
        
        case "List":
            var data = fnData.data;
            var list = data[data[AuthSSL.Listkey]];
            
            for(i in json) {
                var row = json[i];
                for(k in row) {
                    list[i][k] = row[k];
                }
            }
            
            if(typeof(fnData.callback_fn) == "function")
                fnData.callback_fn(fnData.data);
            break;
         
        case "Row":
            var data = fnData.data;

            try {
                for(k in json) {
                    eval("data."+k.replace(/__/, '.')+"=json[k];");
                }
            } catch(e) {}
            
            if(typeof(fnData.callback_fn) == "function")
                fnData.callback_fn(fnData.data);
            break;
    }
    
    iDecodeStatus++;    
        
    AuthSSL.data[AuthSSL_id] = undefined;

}

