var NS4;
var IE4;
if (document.all) {
    IE4 = true;
    NS4 = false;
} else {
    IE4 = false;
    NS4 = true;
}

var isWin = (navigator.appVersion.indexOf("Win") != -1)
var agent = navigator.userAgent.toLowerCase();
var isIE = (agent.indexOf("msie") != -1) && (agent.indexOf("opera") == -1) && (agent.indexOf("webtv") == -1);

var frmMinHeight;
var applyMinSize = false;
var frmMaxWidth;
var frmMaxHeight;
var applyMaxSize = false;

function setMinSize(width, height) {
    frmMinWidth = width;
    frmMinHeight = height
    applyMinSize = true;
}

function setMaxSize(width, height) {
    frmMaxWidth = width;
    frmMaxHeight = height
    applyMaxSize = true;
}


/*
* 기능설명 : iframe 자동리사이징
* Cross Browser에서 작동
*/
function resizeIframe(name) {
    if (name == null || name == "") {
        name = "myframeapps";
    }
        
    try {
        if (IE4) {
            var oBody   = document.frames(name).document.body;
		} else {
            var oBody = document.getElementById(name).contentDocument.body;
		}

        var oIFrame = document.getElementById(name);

        var frmWidth  = oBody.scrollWidth;
        var frmHeight = oBody.scrollHeight;

        if (applyMinSize) {
            frmWidth  = Math.max(frmWidth, frmMinWidth);
            frmHeight = Math.max(frmHeight, frmMinHeight);
        }

        if (applyMaxSize) {
            frmWidth  = Math.min(frmWidth, frmMaxWidth);
            frmHeight = Math.min(frmHeight, frmMaxHeight);
        }

        oIFrame.style.height = frmHeight;
        oIFrame.style.width = frmWidth;
    } catch (e) {}
}


/*
* 기능설명 : iframe 자동리사이징 (Parent Frame)
* Cross Browser에서 작동
*/
function parentResizeIframe(name) {
    if (parent && parent != this && parent.resizeIframe != null) {
        parent.resizeIframe(name);
    }
}

/*
* 기능설명 : iframe 자동리사이징 (Parent의 Parent Frame)
* Cross Browser에서 작동
*/
function grandParentResizeIframe(name) {
    if (parent.parent && parent.parent != this && parent.parent.resizeIframe != null) {
        parent.parent.resizeIframe(name);
    }
}


/*
* 기능설명 : iframe 자동리사이징 & 상단으로 스크롤링
*/
function autoResizeiFrame() {

    parentResizeIframe(self.name);
	widnowScrollTop();

    /* Cross Browser 대응을 위해 변경
    var obj;
    if(parent != null) {
        obj = parent.document.all[self.name];
        if(obj != null) {
            //obj.style.pixelWidth = self.document.body.scrollWidth;
            obj.style.pixelHeight = self.document.body.scrollHeight;
            parent.scrollTo(0,0);
        }
        self.scrollTo(0,0);
    }
    */
}


/*
* 기능설명 : iframe 자동리사이징
*/
function autoResizeOnlyiFrame() {
    
	parentResizeIframe(self.name);

    /* Cross Browser 대응을 위해 변경
    var obj;
    if(parent != null) {
        obj = parent.document.all[self.name];
        if(obj != null) {
            //obj.style.pixelWidth = self.document.body.scrollWidth;
            obj.style.pixelHeight = self.document.body.scrollHeight;
        }
    }
    */
}

/*
* 기능설명 : iframe의 부모창 자동리사이징
*/
function autoResizeOnlyParentiFrame() {
    
    grandParentResizeIframe(parent.name);

    /* Cross Browser 대응을 위해 변경
    var obj;
    if(parent.parent != null) {
        obj = parent.parent.document.all[parent.name];
        if(obj != null) {
            //obj.style.pixelWidth = parent.document.body.scrollWidth;
            obj.style.pixelHeight = parent.document.body.scrollHeight;
        }
    }
    */
}


/*
* 기능설명 : 상단으로 스크롤링
* 부가설명 : IFrame내에서 페이지 이동시 페이지 위치가 중간부터 보이는 것 방지하기 위해...
*/
function widnowScrollTop() {
    parent.scrollTo(0,0);
}


/*
* 기능설명 : 팝업
* 파라미터 : URL, 팝업이름, 왼쪽위치, 상단위치, 팝업가로사이즈, 팝업세로사이즈, 툴바, 메뉴바, 상태바, 스크롤바, 리사이징, 로케이션바
*/
function popup_window_common(url, name, left, top, width, height, toolbar, menubar, statusbar, scrollbar, resizable, location) {
    toolbar_str = toolbar ? 'yes' : 'no';
    menubar_str = menubar ? 'yes' : 'no';
    statusbar_str = statusbar ? 'yes' : 'no';
    scrollbar_str = scrollbar ? 'yes' : 'no';
    resizable_str = resizable ? 'yes' : 'no';
    location_str = location ? 'yes' : 'no';

    /*alert("toolbar : " + toolbar_str);
    alert("menubar : " + menubar_str);
    alert("statusbar : " + statusbar_str);
    alert("scrollbar : " + scrollbar_str);
    alert("resizable : " + resizable_str);
    alert("location : " + location_str);*/

    var mdWindow = null;
    mdWindow = window.open(url, name, 'left='+left+',top='+top+',width='+width+',height='+height+',toolbar='+toolbar_str+',menubar='+menubar_str+',status='+statusbar_str+',scrollbars='+scrollbar_str+',resizable='+resizable_str+',location='+location_str);
    if(!mdWindow){
        alert("팝업차단을 해제해주세요.");
        return false;
    }
    mdWindow.focus();
}


/*
* 기능설명 : 팝업
* 파라미터 : URL
*/
function popup_window_common2(url) {
    var mdWindow = null;
    mdWindow = window.open(url);
    if(!mdWindow){
        alert("팝업차단을 해제해주세요.");
        return false;
    }
    mdWindow.focus();
}


/*
* 로그인
* 파라미터 : 로그인/로그아웃 in,out), 타겟(_self, _parent)
*/
function login(flag, targetwindow) {
	//alert("aa");
    var szWSOCode = "CBTOUR";
    var this_location = self.location.href;
    if (parent.myframeapps) this_location = parent.location.href;

    if (flag == 'in') {
        //self.location.href = '/apps/login.do?doprocess=loginform&loginUrl=' + this_location;
        //parent.location.href = '/content_kor/mn90/mn90_02.jsp?doprocess=loginform&loginUrl=' + this_location;
        //parent.location.href = 'http://sso.cb21.net/CBSSO/scr/login.jsp?szWSOCode=' +szWSOCode+ '&szRtnUrl=' +this_location;
        parent.location.href = 'http://sso.cb21.net/CBSSO/scr/login.jsp?szWSOCode=' +szWSOCode+ '&szRtnUrl=http://www.cbtour.net/apps/login.do?doprocess=login&loginUrl='+this_location;
    } else {
        //self.location.href = '/apps/login.do?doprocess=logout';
        //parent.location.href = '/content_kor/mn90/mn90_02.jsp?doprocess=logout';
        //parent.location.href = 'http://sso.cb21.net/CBSSO/reqSSOLogout.sso?szWSOCode=' +szWSOCode+ '&szRtnUrl=http://www.cbtour.net/apps/login.do?doprocess=logout';
        parent.location.href = 'http://sso.cb21.net/CBSSO/reqSSOLogout.sso?szWSOCode=' +szWSOCode+ '&szRtnUrl=http://www.cbtour.net/apps/login.do?doprocess=logout';
    }
}

/*
function Login(state) {
    if (state == 'out') {
        var logouturl = '/apps/login.do?doprocess=logout';
        self.location.href = logouturl;
    } else {
        var loginurl = document.location.href;

        for (i=0; i<10; i++) {
            if (loginurl.indexOf('&') > -1)
                loginurl = loginurl.replace('&','!');
            else
                break;
        }

        var loginurl = '/content_kor/login/login.jsp?loginUrl='+loginurl;
        self.location.href = loginurl;
    }
}
*/


/*
* URL 이동
* 타겟, URL
*/
function moveUrl(targetwindow, moveurl) {
    targetwindow.location.href = moveurl;
}


/*
* 기능설명 : 플래쉬 삽입
* 파라미터 : 파일경로, 가로, 세로, 아이디, 배경색, 윈도우모드
*/
function insertFlash(url, w, h, id, bg, win){
    var flashStr=
        "<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='"+w+"' height='"+h+"' id='"+id+"' align='middle'>"+
        "<param name='movie' value='"+url+"' />"+
        "<param name='wmode' value='"+win+"' />"+
        "<param name='menu' value='false' />"+
        "<param name='quality' value='high' />"+
        "<param name='bgcolor' value='"+bg+"' />"+
        "<embed src='"+url+"' wmode='"+win+"' menu='false' quality='high' bgcolor='"+bg+"' width='"+w+"' height='"+h+"' name='"+id+"' align='middle' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' />"+
        "</object>";
    document.write(flashStr);
}


/*
* 기능설명 : 스크립트 삽입
* 파라미터 : 스크립트
*/
function activateActiveX(script) {
    document.write(script);
}


/*
* 기능설명 : 텍스트 Area Validater (ajax)
* 파라미터 :  chkFrm     : 체크할 폼이름
             maxSize    : 최대값
             rtnFrm     : 현재 문자길이를 표현할 폼
*/
function countByte(chkFrm, maxSize, rtnFrm) {
    var str = chkFrm.value;
    var paramName1 = encodeURIComponent("maxSize");     // UTF-8 인코딩
    var paramValue1 = encodeURIComponent(maxSize);      // UTF-8 인코딩
    var paramName2 = encodeURIComponent("inputStr");    // UTF-8 인코딩
    var paramValue2 = encodeURIComponent(str);          // UTF-8 인코딩
    var url = '/common/etc/calculateByte.jsp?' +paramName1+ '=' +paramValue1+ '&' +paramName2+ '='+paramValue2;
    request.open("GET", url, true);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                var response = request.responseText;
                if (rtnFrm!=null) {
                    rtnFrm.value = response;
                }
            } else {
                alert("Error: status code is " + request.status);
            }
        }
    }
    request.send(null);

    if(rtnFrm.value > maxSize) {
        chkFrm.blur();
        chkFrm.focus();
        alert("입력범위를 초과하였습니다.");
        countChar(chkFrm, maxSize, rtnFrm);
    }
}


/*
* 기능설명 : 텍스트 Area Validater
* 파라미터 :  chkFrm     : 체크할 폼이름
             maxSize    : 최대값
             rtnFrm     : 현재 문자길이를 표현할 폼
*/
function checkChar(chkfrm, chksize, rtnfrm){
    var str, msg;
    var len = 0;
    var temp;
    var count = 0;

    msg = chkfrm.value;
    str = new String(msg);
    len = str.length;

    for (k=0 ; k<len ; k++){
        temp = str.charAt(k);

        if (escape(temp).length > 4) {
            count += 3;
        } else if (temp == '\r' && str.charAt(k+1) == '\n') { // \r\n일 경우
            count += 2;
        } else if (temp != '\n') {
            count++;
        }
    }

    rtnfrm.value = count;

    if(count > chksize) {
        chkfrm.blur();
        chkfrm.focus();
        alert(chksize + "Byte 까지만 등록이 가능합니다.");
        countChar(chkfrm, chksize, rtnfrm);
        return false;
    } else {
        return true;
    }
}


/*
* 기능설명 : 텍스트 Area Validater (문자길이 카운트)
* 파라미터 :  chkFrm     : 체크할 폼이름
             maxSize    : 최대값
             rtnFrm     : 현재 문자길이를 표현할 폼
*/
function countChar(chkfrm, chksize, rtnfrm) {
    var str,msg;
    var len=0;
    var temp;
    var count;
    count = 0;

    msg = chkfrm.value;
    str = new String(msg);
    len = str.length;

    for(k=0 ; k<len ; k++) {
        temp = str.charAt(k);

        if(escape(temp).length > 4) {
            count += 3;
        } else if (temp == '\r' && str.charAt(k+1) == '\n') { // \r\n일 경우
            count += 2;
        } else if(temp != '\n') {
            count++;
        }
        if(count > chksize) {
            str = str.substring(0,k);
            break;
        }
    }
    chkfrm.value = str;
    checkChar(chkfrm, chksize, rtnfrm);
}


/*
* 기능설명 : 카운터 등록 페이지 이동 (관리자)
* 파라미터 : cmUrl : 이동경로
* 파라미터 : URL, 팝업이름, 왼쪽위치, 상단위치, 팝업가로사이즈, 팝업세로사이즈, 툴바, 메뉴바, 상태바, 스크롤바, 리사이징, 로케이션바
*/
function setCounter(cmurl) {
    var v_url='/content_kor/mn99/mn99_04_01.jsp?cmUrl='+ cmurl;
    //var v_url='/apps/ctmt.do?doprocess=insertform&cmUrl='+ cmurl;
    popup_window_common(v_url, 'COUNTERWINDOW', 50, 300, 700, 630, 0, 0, 0, 1, 1, 0);
}




/*
* 기능설명 : 숫자를 자리수마다 콤마(,) 찍어준다.
* 파라미터 : str : 숫자
            cnt : 자리수
*/
function setCommaNumber(str, cnt) {
    str = ""+str+"";
    var pointidx = str.indexOf(".");
    var pointstr = '';
    if (pointidx>0) {
        pointstr = str.substring(pointidx,str.length);
        str = str.substring(0,pointidx);
    }
    var retValue = "";
    for(i=0; i<str.length; i++) {
        if(i > 0 && (i%cnt)==0) {
            retValue = str.charAt(str.length - i -1) + "," + retValue;
        } else {
            retValue = str.charAt(str.length - i -1) + retValue;
        }
    }
    retValue = retValue + pointstr;
    return retValue;
}


/*
* 기능설명 : 소수점 몇째자리까지만 출력 (반올림해서 출력)
* 파라미터 : str : 숫자
            cnt : 소수점자릿수
*/
function setPointNumber(str, cnt) {
    retValue = Math.round(str * (Math.pow(10,cnt))) / (Math.pow(10,cnt));
    return retValue;
}
              
                              
/*
* 기능설명 : 문자열에서 줄바꿈을 <br>태그로 변환
* 파라미터 : str
*/
function nl2br(src) {
    var tmp
    if (src == "") tmp =  "&nbsp;";
    else tmp = changeStr(src, "\n", "<br>");
    return tmp;
}


/*
* 기능설명 : 문자열 변환 (src 에서 s1을 s2로 변환)
* 파라미터 : src, s1, s2
*/
function changeStr(src,s1,s2) {
    var tmp;
    if (src.indexOf(s1) == -1)
        return src;

    while( src.indexOf(s1) > -1) {
        tmp = src.substr(0, src.indexOf(s1));
        tmp += s2;
        tmp += src.substr(src.indexOf(s1)+s1.length,src.length);
        src = tmp;
    }
    return tmp;
}


/*
* 기능설명 : 외국어페이지이동
*/
function foreignSite(form) {
    var myindex = form.foreign.selectedIndex;
    form.foreign.selectedIndex = 0;
    onchange = window.open(form.foreign.options[myindex].value, 'foreignSite');
    onchange.focus();
    //parent.location.href = form.foreign.options[myindex].value;
}


/*
* 기능설명 : 폼메일
*/
function sendFormMail(rmail, rname) {
    var rname = encodeURIComponent(rname);      // 한글인코딩 처리
    var url = '/apps/fmlg.do?doprocess=sendform&flrem='+rmail+'&flrnm='+rname;
    popup_window_common(url, 'sendFormMail', 10, 10, 400, 450, 0, 0, 0, 1, 0, 0);
    //function popup_window_common(url, name, left, top, width, height, toolbar, menubar, statusbar, scrollbar, resizable, location) {
}


/*
* 기능설명 : 관광지도 (사용자화면)
*/
function goTourMap(x, y, name) {
    pos_w = screen.availWidth;  // 해상도 가로사이즈
    pos_h = screen.availHeight; // 해상도 세로사이즈
    size_w = 800;
    size_h = 675;
    var mapurl = 'http://cbtour.visitkorea.or.kr/Scripts/Map/SearchMap.aspx';
    //var mapparam = 'beginCmd=mapurl&pos=' +x+y+ '6&cpname=' +encodeURIComponent(name);
    //var mapparam = 'beginCmd=mapurl&pos=' +x+y+ '6&cpname=' +name;
    var mapparam = 'beginCmd=mapurl&pos=' +x+y+ '6';
    mapurl = mapurl + '?' + mapparam;
    //alert(mapurl);
    popup_window_common(mapurl, 'TOURMAP_WIN_POPUP', (pos_w/2)-(size_w/2), (pos_h/2)-(size_h/2), size_w, size_h, 0, 0, 1, 1, 1, 0);
}


/*
* 기능설명 : 관광지도 (관리자화면)
*/
function goTourAdminMap(x, y, name) {
    pos_w = screen.availWidth;  // 해상도 가로사이즈
    pos_h = screen.availHeight; // 해상도 세로사이즈
    size_w = 800;
    size_h = 695;
    var mapurl = 'http://cbtour.visitkorea.or.kr/Scripts/Common/MapAdmin.aspx';
    var mapparam = 'xmap=' +x+ '&ymap=' +y+ '&level=6';
    mapurl = mapurl + '?' + mapparam;
    //alert(mapurl);
    popup_window_common(mapurl, 'TOURMAP_WIN_POPUP', (pos_w/2)-(size_w/2), (pos_h/2)-(size_h/2), size_w, size_h, 0, 0, 1, 1, 0, 0);
}

/* 
 * 일정관리 에디터 저장 관련
 

var fullURL = location.href;
var splitIndex = fullURL.indexOf('/',7);
var currentHost = "";

if(splitIndex != -1) {
	currentHost = fullURL.substring(0, splitIndex);
} else {
	currentHost = fullURL;
}

function editorSave(strValue) {
	temp = strValue;
	temp = truncateEditorURL(temp);
	temp = truncateSelfURL(temp, fullURL);
	temp = truncateSelfHost(temp, currentHost);
	return temp;
}

function truncateSelfHost(strValue, tURL) {
	urlRe = /([\/|\?|\||\.|\*|\^|\$|\+|\(|\)|\[|\]|\{|\}|\-])/g;
	tURL = tURL.replace(urlRe, "\\$1");

	eval("repRe = /("+tURL+")/gi");
	strValue = strValue.replace(repRe, "");
	return strValue;
}

function truncateSelfURL(strValue, tURL) {
	urlRe = /([\/|\?|\||\.|\*|\^|\$|\+|\(|\)|\[|\]|\{|\}|\-])/g;
	tURL = tURL.replace(urlRe, "\\$1");

	eval("repRe = /(<a[ ]+href=[ ]*[\"']*)("+tURL+")(#[^>]*>)/gi");
	strValue = strValue.replace(repRe, "$1$3");
	return strValue;
}

function truncateEditorURL(strValue) {
	return truncateSelfURL(strValue, currentHost+"/common/editor/editor.html");
}
*/

/**
 * 히든 파레메터를 생성하여 주거나 수정해준다.(append)
 * @param form
 * @param inputName
 * @param inputValue
 * @return
 */
function addParam(form, inputName, inputValue){
	if(form.size()>0&&''!=inputName){
		form = form.eq(0);
		var input = form.find(':input[name='+inputName+']');
		if(input.size()>0){
			input.val(inputValue);
		}else{
			form.append('<input type="hidden" name="'+inputName+'" value="'+inputValue+'">');
		}
	}
}

/**
 * 히든 파레메터를 생성하여 주거나 수정해준다.(appendTo)
 * @param form
 * @param inputName
 * @param inputValue
 * @return
 */
function addParam2(form,inputName,inputValue){
	$("<input type='hidden' name='"+inputName+"' value='"+inputValue+"' />").appendTo(form);
}


function goUrl(opt){	
	var url=$(opt).val();
	if(url!='')
		window.open($(opt).val(),'_blank');
	else{
		alert('이동할 사이트를 선택하세요!');
		return false;
	}
	
}
