//////////////////////////////////////////// Ifram auto height /////////////////////////////////////////////////
// Browse Type
// IE Script
var IE = false ;
if (window.navigator.appName.indexOf("Explorer") !=-1)
{
	IE = true;
}

// Iframe 내에서 호출하여 페이지 높이를 맞춘다.
function cm_paperInit(minHeight)
{
	try
	{
		var timeArray = new Array(0, 200, 500, 1500, 3500, 7000, 12000, 20000);
		//alert("1_cm_paperInit, timeArray.length="+timeArray.length);
		for(var i=0; i < timeArray.length; i++)
			setTimeout('_cm_paperInit(\''+minHeight+'\')', timeArray[i]);

	}catch (e) {}
}

// Iframe 내에서 호출하여 페이지 높이를 맞춘다.
function _cm_paperInit(minHeight)
{
	try
	{
		//	alert("2_cm_paperInit");
		if(minHeight==null) minHeight = 0;
		if (self.name!=null && self.name!="" && parent!=null
	    	&& parent._cm_resizeIframe!=null)
	    {
	        parent._cm_resizeIframe(self.name, minHeight);
	    }


	}catch (e) {}
}

// 직접사용은 금함. cm_paperInit()를 사용할것.
function _cm_resizeIframe(name, minHeight)
{
	//alert("cm_resizeIframe, name="+name);
	if(minHeight==null) minHeight = 0;
    if(name==null || name=="") return;

    try
    {
        if (IE)
            var oBody = document.frames(name).document.body;
		else
            var oBody = document.getElementById(name).contentDocument.body;

		var oIFrame = document.getElementById(name);

        var frmWidth  = oBody.scrollWidth;// + (oBody.offsetWidth - oBody.clientWidth);
        var frmHeight = oBody.scrollHeight;// + (oBody.offsetHeight - oBody.clientHeight);

		oIFrame.style.height = frmHeight;

    }catch (e) {}

}









//////////////////////////////////////////// 폼 검증 함수 /////////////////////////////////////////////////
function checkForm(f) {
    var fLen = f.elements.length;
    var fObj;   // 폼 요소
    var fTyp;   // 폼 요소 Type
    var fVal;   // 폼 요소 Value
    var fMsg;   // 경고 메시지 속성
    var fNum;   // 숫자만 입력 속성
    var fMax;   // 최대 길이 지정
    var fMin;   // 최소 길이 지정
    var fMxN;   // 최대값 지정
    var fMnN;   // 최소값 지정
    var fMal;   // 메일 FORMAT

	if (!IE) return true;

    for (i=0;i<fLen;i++) {
        fObj = f.elements[i];
        fTyp = toUpperCase(fObj.getAttribute("type"));
        fVal = fObj.getAttribute("value");
        fMsg = fObj.getAttribute("msg");        // 경고 메시지
        fID = fObj.getAttribute("chkid");     // 영어 숫자혼합 기입 가능하도록
        fNum = fObj.getAttribute("chknum");     // 숫자만 기입 가능하도록
        fMax = fObj.getAttribute("maxlen");     // 최대 입력글자수 제한
        fMin = fObj.getAttribute("minlen");     // 최소 입력글자수 제한
        fMxN = fObj.getAttribute("maxnum");     // 최대 숫자 제한
        fMnN = fObj.getAttribute("minnum");     // 최소 숫자 제한
        fMal = fObj.getAttribute("chkmail");    // 이메일 체크
        fDU = fObj.getAttribute("chkuserid");    // 아이디 중복검사
        fJU = fObj.getAttribute("chkjumin");    // 주민 중복검사

        if (fMsg != null && (fTyp == "TEXT" || fTyp == "HIDDEN" || fTyp == "TEXTAREA" || fTyp == "PASSWORD") && fVal.replace(/ /gi,"") == "") {
            alert(fMsg + " 입력해 주세요");
            if (fTyp != "HIDDEN") {fObj.focus();}
            return false;
        }
        if (fMsg != null && (fTyp == "SELECT-ONE" || fTyp == "SELECT-MULTIPLE") && fVal =="") {
            alert(fMsg + " 선택해 주세요");
            fObj.focus(); return false;
        }
        if (fMsg != null && (fTyp == "RADIO" || fTyp == "CHECKBOX") && checkChecked(fObj) == false) {
            alert(fMsg + " 선택해 주세요");
            fObj.focus(); return false;
        }

        if (fNum != null && isNaN(fVal)) {
            alert("숫자로만 입력해 주세요");
            fObj.focus(); return false;
        }
        if (fID != null && checkID(fVal)) {
            alert("아이디는 영어와 숫자 혼합형으로 입력해 주세요");
            fObj.focus(); return false;
        }
        if (fMax != null && fMax < getLen(fVal)) {
            alert("입력된 글자수가 "+fMax+"자보다 작아야합니다.\n(영문 "+fMax+"자, 한글 "+Math.floor(fMax/2)+"자 까지 가능합니다.)");
            fObj.focus(); return false;
        }
        if (fMin != null && fMin > getLen(fVal)) {
            alert("입력된 글자수가 "+fMin+"자보다 커야합니다.");
            fObj.focus(); return false;
        }
        if (fMxN != null && parseInt(fMxN) < parseInt(fVal)) {
            alert("입력된 숫자는 "+fMxN+"보다 작아야합니다.");
            fObj.focus(); return false;
        }
        if (fMnN != null && parseInt(fMnN) > parseInt(fVal)) {
            alert("입력된 숫자는 "+fMnN+"보다 커야합니다.");
            fObj.focus(); return false;
        }
        if (fMal != null && checkEmail(fVal) == false && fVal != "") {
            alert("이메일 주소가 올바르지 않습니다");
            fObj.focus(); return false;
        }

        if (fDU != null && fVal != "") {
            check_value("user_id", fVal)
            fObj.focus(); return false;
        }

        if (fJU != null && fVal != "") {
            check_value("jumin", fVal)
            fObj.focus(); return false;
        }
    }
    return true;
}


// 배열 요소일 경우 checked 된것이 있는지 확인
function checkChecked(obj) {
    var objnm = obj.name;
    var oElem = eval("document.all."+objnm);
    var ret = false;

    if (typeof(oElem.length) == "undefined") {
        if (oElem.checked) {
            ret = true;
        }
    } else {
        for (var i=0;i<oElem.length;i++) {
            if (oElem[i].checked) {
                ret = true;
            }
        }
    }
    return ret;
}

// 영어 숫자 혼합인지 체크(한글안됨)
function checkID(str){

	// "영문 + 숫자" 조합 체크
	re=/[^a-z0-9]+|^([a-z]+|[0-9]+)$/i;

	// "첫문자 영문 + 영문 + 숫자" 조합 체크
	//var re=/^[^a-z]|[^a-z0-9]+|^([a-z]+|[0-9]+)$/i;

	if(re.test(str) == true) return true;
	else return false;
}

// 이메일 유효성 체크
function checkEmail(str){
    var reg = /^((\w|[\-\.])+)@((\w|[\-\.])+)\.([A-Za-z]+)$/;
    if (str.search(reg) != -1) {
        return true;
    }
    return false;
}
// 문자 길이 반환 (영문 1byte, 한글 2byte 계산)
function getLen(str) {
    var len;
    var temp;

    len = str.length;
    var tot_cnt = 0;

    for(k=0;k < len;k++){
        temp = str.charAt(k);
        if(escape(temp).length > 4)
            tot_cnt += 2;
        else
            tot_cnt++;
    }
    return tot_cnt;
}
// 대문자 변환 ex) toUpperCase(문자)
function toUpperCase(str) {
    var ret;
    str != null ? ret = str.toUpperCase() : ret = "";
    return ret;
}





function check_value(type, obj) {

	if(type == 'user_id') {

		var value = obj.value;

		/*
		if(checkID(value)) {
			alert("아이디는 영어와 숫자 혼합형으로 입력해 주세요");
			document.getElementById("serverMsg_id").innerHTML = "";
			//document.getElementsByName("user_id")[0].focus();
			obj.focus();
			return false;
		*/
		if (value == "") {
			document.getElementById("serverMsg_id").innerHTML = "";
			return false;
		}
		poststr = "type=" + type + "&value=" + value;

		req = newXMLHttpRequest();
		req.onreadystatechange = processUserid;
		req.open("POST", "main_popup.html?mode=duplicate", true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(poststr);


	} else if(type == 'nick') {

		var value = obj.value;

		if (value == "") {
			document.getElementById("serverMsg_nick").innerHTML = "";
			return false;
		}
		poststr = "type=" + type + "&value=" + value;

		req = newXMLHttpRequest();
		req.onreadystatechange = processNick;
		req.open("POST", "main_popup.html?mode=duplicate", true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(poststr);


	} else if(type == "jumin") {

		f1 = document.getElementsByName("jumin1")[0].value;
		f2 = document.getElementsByName("jumin2")[0].value;

		var value = f1+f2;

		if(!check_juminno(value)) {
			document.getElementsByName("jumin1")[0].value = '';
			document.getElementsByName("jumin2")[0].value = '';
			document.getElementById("serverMsg_jumin").innerHTML = "";
			obj.focus();
			return false;
		}
		poststr = "type=" + type + "&value=" + value;

		req = newXMLHttpRequest();
		req.onreadystatechange = processJumin;
		req.open("POST", "main_popup.html?mode=duplicate", true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(poststr);

	} else if(type == "email") {

		var value = obj.value;

		if(checkEmail(value) == false && value != "") {
			alert("이메일 주소가 올바르지 않습니다");
			document.getElementById("serverMsg_email").innerHTML = "";
			document.getElementsByName("email")[0].focus();
			//obj.focus();
			return false;
		} else if (value == "") {
			document.getElementById("serverMsg_email").innerHTML = "";
			return false;
		}
		poststr = "type=" + type + "&value=" + value;

		req = newXMLHttpRequest();
		req.onreadystatechange = processEmail;
		req.open("POST", "main_popup.html?mode=duplicate", true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(poststr);

	}
}

function newXMLHttpRequest() {
	var xmlreq = false;
	if (window.XMLHttpRequest) {
		xmlreq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
			}
		}
	}
	return xmlreq;
}

function processUserid() {
    if (req.readyState == 4) {
        if (req.status == 200) {
			String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,'') };
			returned = req.responseText.trim();
			if(returned == "FAIL") {
				document.getElementById("serverMsg_id").innerHTML = "<font color='red'>이미 사용중인 아이디 입니다</font>";
				document.getElementsByName("user_id")[0].focus();
			} else if(returned == "TRUE") {
				document.getElementById("serverMsg_id").innerHTML = "<font color='#3366CC'>사용 가능한 아이디 입니다</font>";
			}
        } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
        }
    }
}




function processNick() {
    if (req.readyState == 4) {
        if (req.status == 200) {
			String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,'') };
			returned = req.responseText.trim();
			if(returned == "FAIL") {
				document.getElementById("serverMsg_nick").innerHTML = "<font color='red'>이미 사용중인 필명 입니다</font>";
				document.getElementsByName("nick")[0].focus();
			} else if(returned == "TRUE") {
				document.getElementById("serverMsg_nick").innerHTML = "<font color='#3366CC'>사용 가능한 필명 입니다</font>";
			}
        } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
        }
    }
}



function processJumin() {
    if (req.readyState == 4) {
        if (req.status == 200) {
			String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,'') };
			returned = req.responseText.trim();
			if(returned == "FAIL") {
				document.getElementById("serverMsg_jumin").innerHTML = "<font color='red'>이미 등록된 주민등록번호 입니다</font>";
				document.getElementsByName("jumin1")[0].value = '';
				document.getElementsByName("jumin2")[0].value = '';
				document.getElementsByName("jumin1")[0].focus();
			} else if(returned == "TRUE") {
				document.getElementById("serverMsg_jumin").innerHTML = "<font color='#3366CC'>확인 되었습니다</font>";
			}
        } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
        }
    }
}




function processEmail() {
    if (req.readyState == 4) {
        if (req.status == 200) {
			String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,'') };
			returned = req.responseText.trim();
			if(returned == "FAIL") {
				document.getElementById("serverMsg_email").innerHTML = "<font color='red'>이미 사용중인 이메일 입니다</font>";
				document.getElementsByName("email")[0].focus();
			} else if(returned == "TRUE") {
				document.getElementById("serverMsg_email").innerHTML = "<font color='#3366CC'>확인 되었습니다</font>";
			}
        } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
        }
    }
}




// 폼값 집어넣기
function InnerSetValue(input_name,input_value) {
  if(!(fn = document.getElementById(input_name))) {
    fn = document.getElementsByName(input_name)[0];
  }
  if(fn!=null && input_value != '') {
    if(fn.type=='radio') {
      count = document.getElementsByName(input_name).length;
      for(i=0;i<count;i++) {
        if(document.getElementsByName(input_name)[i].value==input_value) {
          document.getElementsByName(input_name)[i].checked=true;
        }
      }
    } else {
      switch (fn.type) {
        case 'checkbox' :
          if(fn.value==input_value) {
            fn.checked = true;
          }
          break;
        case 'select-one' :
          fn.value = input_value;
          if(fn.value=='') {
            fn.option[0].chekced = true;
          }
          break;
        case 'text' :
          fn.value = input_value;
          break;
        default :
      }
    }
  }
}




// 재외국인 번호 체크
function check_fgnno(fgnno) {
        var sum=0;
        var odd=0;
        buf = new Array(13);
        for(i=0; i<13; i++) { buf[i]=parseInt(fgnno.charAt(i)); }
        odd = buf[7]*10 + buf[8];
        if(odd%2 != 0) { return false; }
        if( (buf[11]!=6) && (buf[11]!=7) && (buf[11]!=8) && (buf[11]!=9) ) {
                return false;
        }
        multipliers = [2,3,4,5,6,7,8,9,2,3,4,5];
        for(i=0, sum=0; i<12; i++) { sum += (buf[i] *= multipliers[i]); }
        sum = 11 - (sum%11);
        if(sum >= 10) { sum -= 10; }
        sum += 2;
        if(sum >= 10) { sum -= 10; }
        if(sum != buf[12]) { return false }
        return true;
}

// 주민번호 체크
function check_juminno(juminno) {
        if(juminno=="" || juminno==null || juminno.length!=13) {
                alert("주민등록번호를 적어주세요.");
                return false;
        }
        var jumin1 = juminno.substr(0,6);
        var jumin2 = juminno.substr(6,7);
        var yy         = jumin1.substr(0,2);        // 년도
        var mm = jumin1.substr(2,2);        // 월
        var dd = jumin1.substr(4,2);        // 일
        var genda = jumin2.substr(0,1);        // 성별
        var msg, ss, cc;

        // 숫자가 아닌 것을 입력한 경우
        if (!isNumeric(jumin1)) {
                alert("주민등록번호 앞자리를 숫자로 입력하세요.");
                return false;
        }
        // 길이가 6이 아닌 경우
        if (jumin1.length != 6) {
                alert("주민등록번호 앞자리를 다시 입력하세요.");
                return false;
        }
        // 첫번째 자료에서 연월일(YYMMDD) 형식 중 기본 구성 검사
        if (yy < "00" || yy > "99" ||
                mm < "01" || mm > "12" ||
                dd < "01" || dd > "31") {
                alert("주민등록번호 앞자리를 다시 입력하세요.");
                return false;
        }
        // 숫자가 아닌 것을 입력한 경우
        if (!isNumeric(jumin2)) {
                alert("주민등록번호 뒷자리를 숫자로 입력하세요.");
                return false;
        }
        // 길이가 7이 아닌 경우
        if (jumin2.length != 7) {
                alert("주민등록번호 뒷자리를 다시 입력하세요.");
                return false;
        }
        // 성별부분이 1 ~ 4 가 아닌 경우
        if (genda < "1" || genda > "4") {
                alert("주민등록번호 뒷자리를 다시 입력하세요.");
                return false;
        }
        // 연도 계산 - 1 또는 2: 1900년대, 3 또는 4: 2000년대
        cc = (genda == "1" || genda == "2") ? "19" : "20";
        // 첫번째 자료에서 연월일(YYMMDD) 형식 중 날짜 형식 검사
        if (isYYYYMMDD(parseInt(cc+yy), parseInt(mm), parseInt(dd)) == false) {
                alert("주민등록번호 앞자리를 다시 입력하세요.");
                return false;
        }
        // Check Digit 검사
        if (!isSSN(jumin1, jumin2)) {
                alert("잘못된 주민등록번호 입니다.");
                return false;
        }
        return true;
}

// 사업자등록번호 체크
function check_busino(vencod) {
        var sum = 0;
        var getlist =new Array(10);
        var chkvalue =new Array("1","3","7","1","3","7","1","3","5");
        for(var i=0; i<10; i++) { getlist[i] = vencod.substring(i, i+1); }
        for(var i=0; i<9; i++) { sum += getlist[i]*chkvalue[i]; }
        sum = sum + parseInt((getlist[8]*5)/10);
        sidliy = sum % 10;
        sidchk = 0;
        if(sidliy != 0) { sidchk = 10 - sidliy; }
        else { sidchk = 0; }
        if(sidchk != getlist[9]) { return false; }
        return true;
}


function isYYYYMMDD(y, m, d) {
        switch (m) {
        case 2:        // 2월의 경우
                if (d > 29) return false;
                if (d == 29) {
                        // 2월 29의 경우 당해가 윤년인지를 확인
                        if ((y % 4 != 0) || (y % 100 == 0) && (y % 400 != 0))
                                return false;
                }
                break;
        case 4:        // 작은 달의 경우
        case 6:
        case 9:
        case 11:
                if (d == 31) return false;
        }
        // 큰 달의 경우
        return true;
}
function isNumeric(s) {
        for (i=0; i<s.length; i++) {
                c = s.substr(i, 1);
                if (c < "0" || c > "9") return false;
        }
        return true;
}
function isLeapYear(y) {
        if (y < 100)
        y = y + 1900;
        if ( (y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0) ) {
                return true;
        } else {
                return false;
        }
}
function getNumberOfDate(yy, mm) {
        month = new Array(29,31,28,31,30,31,30,31,31,30,31,30,31);
        if (mm == 2 && isLeapYear(yy)) mm = 0;
        return month[mm];
}
function isSSN(s1, s2) {
        n = 2;
        sum = 0;
        for (i=0; i<s1.length; i++)
                sum += parseInt(s1.substr(i, 1)) * n++;
        for (i=0; i<s2.length-1; i++) {
                sum += parseInt(s2.substr(i, 1)) * n++;
                if (n == 10) n = 2;
        }
        c = 11 - sum % 11;
        if (c == 11) c = 1;
        if (c == 10) c = 0;
        if (c != parseInt(s2.substr(6, 1))) return false;
        else return true;
}