﻿var request = null;
/*
요청객체를 생성하는 랩퍼함수
매개변수:
reqType: http요청 유형,get또는 post
url : 서버 프로그램 url
asynch: 동기 또는 비동기 모드 선택
respHandle: 반환 값을 처리하는 함수 이름
다섯번째 매개변수(argments[4])는 Post요청시 전송되는 데이터
*/
function httpRequest(reqType, url, asynch, respHandle) {
    try {
        request = new XMLHttpRequest();
    } catch (trymicrosoft) {
        try {
            request = new ActiveXObject("Msxm12.XMLHTTP");
        } catch (othermicrosoft) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                request = false;
            }
        }
    }

    //요청객체가 생성되었는지를 검사
    if (request) {
        //reqType값이 post면 5번째 매개변수는 전송될 데이터
        if (reqType.toLowerCase() != "post") {
            initReq(reqType, url, asynch, respHandle);
        } else {
            //post전송되는 데이터
            var args = arguments[4];
            if (args != null && args.length > 0) {
                initReq(reqType, url, asynch, respHandle, args);
            }
        }
    } else {
        alert("객체생성 실패!!관리자에게 문의하세요.");
    }
}

//생성된 요청 초기화
function initReq(reqType, url, bool, respHandle) {
    try {
        //http응답을 처리할 함수 지정
        request.onreadystatechange = respHandle;
        request.open(reqType, url, bool);
        //reqType의 값이 post면 5번째 매개변수는 전송될 데이터
        if (reqType.toLowerCase() == "post") {
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=euc-kr");
            request.send(arguments[4]);
        } else {
            request.send(null);
        }
    } catch (errv) {
        alert("error:" + errv.message);
    }
}

//쿠키설정
function setCookie(NameOfCookie, value, expiredays) {
    var ExpireDate = new Date();
    ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 60 * 60 * 1000));
    document.cookie = NameOfCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}

function getCookie(NameOfCookie) {
    if (document.cookie.length > 0) {
        begin = document.cookie.indexOf(NameOfCookie + "=");
        if (begin != -1) {
            begin += NameOfCookie.length + 1;
            end = document.cookie.indexOf(";", begin);
            if (end == -1) end = document.cookie.length;
            return unescape(document.cookie.substring(begin, end));
        }
    }
    return null;
}

// 숫자만 입력가능 하게...
function OnlyNumber() {
    if ((event.keyCode < 48) || (event.keyCode > 57))
        event.returnValue = false;
}

//ID 한글 및 특수문자 체크...
function hangul_chk(word) {
    var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";

    for (i = 0; i < word.length; i++) {
        idchecks = word.charAt(i);
        for (j = 0; j < str.length; j++) {
            if (idchecks == str.charAt(j)) {
                break;
            }
            if (j + 1 == str.length) {
                return false;
            }
        }
    }
    return true;
}
//ID 숫자로 시작 체크...
function fnum_chk(word) {
    var str = "1234567890";

    for (i = 0; i < str.length; i++) {
        idchecks = word.charAt(0);
        if (idchecks == str.charAt(i)) {
            return false;
        }
    }
    return true;
}

//스페이스제거
function removeSpace(val) {
    var newVal = "";
    for (rhI = 0; rhI < val.length; rhI++) {
        if (!(val.charAt(rhI) == " ")) newVal = newVal + val.charAt(rhI);
    }
    return newVal;
}

// 길이가 차면 다음 텍스트박스로 포커스 이동....
function NextFocus(arg, len, nextname) {
    argValue = document.getElementById(arg).value;

    if (argValue.length == len) {
        document.getElementById(nextname).focus();
        document.getElementById(nextname).select();
        return;
    }
}

// 폼요소 타입 알아오기
function GetType(el) {
    switch (el.tagName.toLowerCase()) {
        case "select":
            return el.multiple == true ? "multiselect" : "select";
        case "textarea": return "text";
        case "input":
            switch (el.type.toLowerCase()) {
                case "radio": return "radio";
                case "checkbox": return "check";
                case "file": return "file";
                case "text": case "password": return "text";
                case "hidden": return "hidden";
            }
            break;
    }
}

//주민등록번호 체크
function func_jumin(el, value) {
    var pattern = /^([0-9]{6})-?([0-9]{7})$/;
    var num = value ? value : el.value;
    if (!pattern.test(num)) return false;
    num = RegExp.$1 + RegExp.$2;

    var sum = 0;
    var last = num.charCodeAt(12) - 0x30;
    var bases = "234567892345";
    for (var i = 0; i < 12; i++) {
        if (isNaN(num.substring(i, i + 1))) return false;
        sum += (num.charCodeAt(i) - 0x30) * (bases.charCodeAt(i) - 0x30);
    }
    var mod = sum % 11;
    return (11 - mod) % 10 == last ? true : false;
}

// 숫자만
function func_number(el) {
    var pattern = /^[0-9]+$/;
    return pattern.test(el.value) ? true : false;
}

//한글
function func_hangul(el) {
    var pattern = /[가-힝]+$/;
    return pattern.test(el.value) ? true : false;
}

//영문
function func_engonly(el) {
    var pattern = /^[a-zA-Z]+$/;
    return pattern.test(el.value) ? true : false;
}

//문자
function func_charnum(el) {
    var pattern = /^[가-힝a-zA-Z]+$/;
    return pattern.test(el.value) ? true : false;
}

// 비밀번호
function func_passwd(el) {
    var pattern = /^[a-zA-Z0-9]{6,12}$/;
    var patternEng = /[a-zA-Z]/;
    var patternNum = /[0-9]/;
    if (!(pattern.test(el.value) && patternEng.test(el.value) && patternNum.test(el.value))) {
        return false;
    }
    return true;
}

// 아이디
function func_id(el) {
    var pattern = /^[a-zA-Z0-9]{4,13}$/;
    if (!(pattern.test(el.value))) {
        return false;
    }
    return true;
}

// 이메일
function func_email(el, value) {
    var value = value ? value : el.value;
    var pattern = /^[_a-zA-Z0-9-\.]+@[\.a-zA-Z0-9-]+\.[a-zA-Z]+$/;
    return pattern.test(value) ? true : false;
}

var extArray = new Array(".ppt", ".doc");

function checkFileUpload(file) {
    var allowSubmit = false;
    while (file.indexOf("\\") != -1) {
        file = file.slice(file.indexOf("\\") + 1);
        var ext = file.slice(file.indexOf(".")).toLowerCase();

        for (var i = 0; i < extArray.length; i++) {
            if (extArray[i] == ext) {
                allowSubmit = true;
                break;
            }
        }

        if (allowSubmit) {
            return true;
        } else {
            alert((extArray.join("  ")) + " 형태의 파일만 첨부하실 수 있습니다.");
            return false;
        }
    }
}

function openCal(child) {
    window.open('/popup/calendar.asp?child=' + child, '_pop', 'width=200,height=250,scrollbars=no');
}

function setCal(idate, child) {
    document.getElementById(child).value = idate;
}

function pollOk(sitegubun,R_URL) {
    val = "poll"
    var cookie = getCookie(val);
    var chkpoll = $("[name=poll]:checked");

    if (chkpoll.length < 1) {
        alert("투표 항목을 선택하신 후 Click 하세요.");
        return;
    }

	location.href = "/common/inc/poll.asp?point=" + chkpoll.val() + "&sitegubun=" + sitegubun + "&R_URL=" + R_URL ;

    //if (cookie == "" || cookie == null) {
    //} else {
     //   alert("고객님께서는 이미 투표하셨습니다.\n\r감사합니다.");
      //  return;
    //}

    //url = "/common/inc/poll.asp?point=" + chkpoll.val();
    //httpRequest("GET",url,true,pollResponse);
}

function pollResponse() {
    var userTag, answer, xmlReturnVal, board;
    if (request.readyState == 4) {
        if (request.status == 200) {
            xmlReturnVal = request.responseText;
            if (xmlReturnVal == "OK") {
                setCookie('poll', 'cookie_checked', 1);
                alert('참여 해주셔서 감사합니다.');
            }
        } else {
            alert("참여 해주셔서 감사합니다.");
        }
    }
}

//클립보드복사
function setClipBoard(str) {
    window.clipboardData.setData('Text', str);
}

//코드
function GetChpartList(code) {
    if (code != null && code != "" && code != "junall"){
        url = "/include/code_list.asp?code=" + code + "&tcode=01";
        httpRequest("GET", url, true, SetChpartList);
    }
    else if(code == "junall"){
        SelClear("searchpart");
        var ChpartList = document.getElementById("searchpart");
        new_option = new Option("전체", "all");
        ChpartList.options.add(new_option, ChpartList.length);
    }
}

function GetChpartList2(code, tcode) {
    if (code != null && code != "") {
        url = "/include/code_list.asp?code=" + code + "&tcode=" + tcode;
        httpRequest("GET", url, true, SetChpartList2);
    }
}

function GetChpartList3(code) {
    if (code != null && code != "" && code != "junall"){
        url = "/include/code_list.asp?code=" + code + "&tcode=03";
        httpRequest("GET", url, true, SetChpartList);
    }
    else if(code == "junall"){
        SelClear("searchpart");
        var ChpartList = document.getElementById("searchpart");
        new_option = new Option("전체", "all");
        ChpartList.options.add(new_option, ChpartList.length);
    }
}

function SetChpartList() {
    var userTag, answer, xmlReturnVal, board;
    if (request.readyState == 4) {
        if (request.status == 200) {
            var httpData = request.responseText;
            if (httpData != '' && httpData != 'ERROR') {
                var rowSplit = httpData.split('^*/');
                var i;
                var ChpartList = document.getElementById("searchpart");
                SelClear("searchpart");
               new_option = new Option("전체", "all");
               ChpartList.options.add(new_option, ChpartList.length);
                
                for (i = 0; i < rowSplit.length - 1; i++) {
                    var colSplit = rowSplit[i].split('^');
                    new_option = new Option(unescape(colSplit[1]), colSplit[0]);
                    ChpartList.options.add(new_option, ChpartList.length);
                }
                httpData = "";
            }
        } else {
            alert("내부 서버 오류입니다.관리자에게 문의해주세요.");
        }
    }
}

function SetChpartList2() {
    var userTag, answer, xmlReturnVal, board;
    if (request.readyState == 4) {
        if (request.status == 200) {
            var httpData = request.responseText;
            if (httpData != '' && httpData != 'ERROR') {
                var rowSplit = httpData.split('^*/');
                var i;
                var ChpartList = document.getElementById("searchpart");
                SelClear("searchpart");
                new_option = new Option("전체", "all");
                ChpartList.options.add(new_option, ChpartList.length);

                for (i = 0; i < rowSplit.length - 1; i++) {
                    var colSplit = rowSplit[i].split('^');
                    new_option = new Option(unescape(colSplit[1]), colSplit[0]);
                    ChpartList.options.add(new_option, ChpartList.length);
                }
                httpData = "";
                Chsearchpart();
            }
        } else {
            alert("내부 서버 오류입니다.관리자에게 문의해주세요.");
        }
    }
}

function SelClear(selId) {
    var ClearId = document.getElementById(selId);
    while (ClearId.childNodes.length > 0) {
        ClearId.removeChild(ClearId.childNodes[0]);
    }
}

//url
// sStr.URLEncode(), sStr.URLDecode()
String.prototype.URLEncode = function URLEncode() {
    var SAFECHARS = "0123456789" +     // Numeric
     "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
     "abcdefghijklmnopqrstuvwxyz" +
     "-_.!~*'()";     // RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";
    var plaintext = this;
    var encoded = "";
    for (var i = 0; i < plaintext.length; i++) {
        var ch = plaintext.charAt(i);
        if (ch == " ") {
            encoded += "+";    // x-www-urlencoded, rather than %20
        } else if (SAFECHARS.indexOf(ch) != -1) {
            encoded += ch;
        } else {
            var charCode = ch.charCodeAt(0);
            if (charCode > 255) {
                alert("Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
              "(URL encoding only supports 8-bit characters.)\n" +
        "A space (+) will be substituted.");
                encoded += "+";
            } else {
                encoded += "%";
                encoded += HEX.charAt((charCode >> 4) & 0xF);
                encoded += HEX.charAt(charCode & 0xF);
            }
        }
    } // for
    return encoded;
};

String.prototype.URLDecode = function URLDecode() {
    var HEXCHARS = "0123456789ABCDEFabcdef";
    var encoded = this;
    var plaintext = "";
    var i = 0;
    while (i < encoded.length) {
        var ch = encoded.charAt(i);
        if (ch == "+") {
            plaintext += " ";
            i++;
        } else if (ch == "%") {
            if (i < (encoded.length - 2)
     && HEXCHARS.indexOf(encoded.charAt(i + 1)) != -1
     && HEXCHARS.indexOf(encoded.charAt(i + 2)) != -1) {
                plaintext += unescape(encoded.substr(i, 3));
                i += 3;
            } else {
                alert('Bad escape combination near ...' + encoded.substr(i));
                plaintext += "%[ERROR]";
                i++;
            }
        } else {
            plaintext += ch;
            i++;
        }
    } // while
    return plaintext;
};

//글자수
function length_count(filed, max_count, contLen) {
    var str;
    var str_count = 0;
    var cut_count = 0;
    var str_length = filed.value.length;

    for (k = 0; k < str_length; k++) {
        str = filed.value.charAt(k);
        if (escape(str).length > 4) {
            str_count += 2;
        }
        else {
            if (escape(str) == '%0A') {
            }
            else {
                str_count++;
            }
        }

        if (contLen != null && contLen != "") {
            $("#" + contLen).html(max_count+"/"+str_count+" byte");
        }

        if (max_count < str_count) {
            alert("글자수가 " + max_count + " byte 이상은 사용불가능합니다");
            if (escape(str).length > 4) str_count -= 2;
            else str_count--;
            filed.value = filed.value.substring(0, k);
                if (contLen != null && contLen != "") {
                $("#" + contLen).html("500/"+str_count+" byte");
            }
            break;
        }
    }
}

function win_open(nurl,win_name,nleft,ntop,nwidth,nheight,scroll){
	if ( nwidth=='' ) nwidth= 300
	if ( nheight=='' ) nheight= 300
	if ( scroll=='' ) scroll= 'no'
	if ( nleft == '' ) nleft=((screen.availWidth/2)-parseInt(nwidth)/2)
	if ( ntop == '' ) ntop=((screen.availHeight/2)-parseInt(nheight)/2)
	window.open(nurl,win_name,'left='+nleft+',top='+ntop+',width='+nwidth+',height='+nheight+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars='+scroll+',resizable=no');
}

//인쇄
  function print_preview(){
	  PrintForm.FORM_CONTENTS.value = document.all['content'].innerHTML; 
	  win_open('','print_preview','','','620','600','yes')
	  PrintForm.submit();
  }

//게시판 유저인증
function UserPass(reurl) {
    win_open('https://www.mpva.go.kr/include/UserPass.asp?reurl='+reurl, 'userpass', '', '', '750', '400', 'no')
}

//게시물 비밀번호확인 게시물코드,ID,타입,댓글아이디
function pwdChk(TableCode,id,WRT,Reply) {
    url = "/include/pwdChk.asp?TableCode=" + TableCode + "&amp;ID=" + id + "&amp;WRT=" + WRT + "&amp;Reply=" + Reply;
    window.open(url, "pwd", "toolbar=no,menubar=no,scrollbars=no,resizable=no,width=320,height=250,left=500,top=300");
}     

//통합검색
function topSearch(){
	var qt = $("#qt").val();
	if(qt == null || qt == ""){
		alert("검색어를 입력하여 주시기 바랍니다.");
		return;
	}else{
		$("#Rsa_text").val(escape($("#qt").val()));
		document.getElementById("tSearch").submit();
	}
}

function SearchKeyDown(){
	var keycode = window.event.keyCode;
	   if (keycode == 13) {
		   topSearch();
	   }
		return;
}