/*********************************************
* 파일명: lib.validate.js
* 기능: 유연한 자동 폼 검사기
* 만든이: 거친마루 <comfuture@maniacamp.com>
* 날짜: 2002-10-01
**********************************************/

/// 에러메시지 포멧 정의 ///
var NO_BLANK = "Please enter {name}";
var NO_SELECT = "Please select {name}";
var NOT_VALID = "The {name} is not correct.";
var NOT_DOC = "You can only upload the {name} in word file."; 
var NOT_IMG = "You can only upload the {name} in image file."; 
var TOO_LONG = "The length of {name} is exceeded. (Maximum {maxbyte} byte.)";
var USER_MSG = "{name}";
var NOT_VALID_EMAIL = "The {name} is not valid.";

/// 스트링 객체에 메소드 추가 ///
String.prototype.trim = function(str) { 
	str = this != window ? this : str; 
	return str.replace(/^\s+/g,'').replace(/\s+$/g,''); 
}

String.prototype.hasFinalConsonant = function(str) {
	str = this != window ? this : str; 
	var strTemp = str.substr(str.length-1);
	return ((strTemp.charCodeAt(0)-16)%28!=0);
}

String.prototype.bytes = function(str) {
	str = this != window ? this : str;
	for(j=0; j<str.length; j=j+1) {
		var chr = str.charAt(j);
		len += (chr.charCodeAt() > 128) ? 2 : 1
	}
	return len;
}


function validate(form) {

	for (i = 0; i < form.elements.length; i=i+1 ) {
		
		if (form.elements[i].getAttribute('name') == "") continue;
		var el = form.elements[i];
		el.value = el.realValue==null?el.value.trim():el.realValue.trim();				
		var minbyte = el.getAttribute("MINBYTE");
		var maxbyte = el.getAttribute("MAXBYTE");
		var option = el.getAttribute("OPTION");
		var minlength = el.getAttribute("MINLENGTH");
		var maxlength = el.getAttribute("MAXLENGTH");
		var match = el.getAttribute("MATCH");
		var glue = el.getAttribute("GLUE");
		var denyBlank = el.getAttribute("denyBlank");
		var usermsg = el.getAttribute("USERMSG");

		if (el.getAttribute("REQUIRED") != null) {

            if (el.type.toLowerCase() == "radio" || el.type.toLowerCase() == "checkbox") {
            
            	var isValid = false;
            
                if (form.elements[el.name].length) {
					for (j = 0; j < form.elements[el.name].length; j++) {
						if (form.elements[el.name][j].checked) {
							isValid = true;
							break;
						}
					}
				} else {
					if (el.checked) {
						isValid = true;
					}
				}
				if(!isValid){
					if(usermsg=="true") {
						return doError(el,USER_MSG);
					} else {
						return doError(el,NO_SELECT);
					}					
				}
            }
			if (el.type.toLowerCase() == "select") {
                if(!isValidSelect(this,el)) return doError(el,NO_BLANK);
            }
			if (el.value == null || el.value == "") {
				if(usermsg=="true") {
					return doError(el,USER_MSG);
				} else {
					return doError(el,NO_BLANK);
				}					
			}
		}

		if (minbyte != null) {
			if (el.value.bytes() < parseInt(minbyte)) {
				return doError(el,"{name} must be minimum of "+minbyte+" bytes.");
			}
		}

		if (maxbyte != null && el.value != "") {
			var len = 0;
			if (el.value.bytes() > parseInt(maxbyte)) {
				return doError(el,"The length of {name} is exceeded. (Maximum {maxbyte} byte.)");
			}
		}

		if (minlength != null) {
			if (el.value.length < parseInt(minlength)) {
				return doError(el,"{name} must be minimum of "+minlength+" characters.");
			}
		}

		if (maxlength != null && el.value != "") {
			var len = 0;
			if (el.value.length > parseInt(maxlength)) {
				return doError(el,"The number of characters for {name} is exceeded. (Maximum "+maxlength+" characters.)");
			}
		}

		if (match && (el.value != form.elements[match].value)) return doError(el,"{name} does not match.");

		if (option != null && el.value != "") {
			if (el.getAttribute('SPAN') != null) {
				var _value = new Array();
				for (span=0; span<el.getAttribute('SPAN');span=span+1 ) {
					_value[span] = form.elements[i+span].value;
				}
				var value = _value.join(glue == null ? '' : glue);
				if (!funcs[option](el,value)) return false;
			} else {
				if (!funcs[option](el)) return false;
			}
		}
	}
	return true;
}

function josa(str,tail) {
	return (str.hasFinalConsonant()) ? tail.substring(0,1) : tail.substring(1,2);
}

function doError(el,type,action) {
	var pattern = /{([a-zA-Z0-9_]+)\+?([가-힝]{2})?}/;
	var name = ( (hname = el.getAttribute("hname")) || (hname = el.getAttribute("ename")) ) ? hname : el.getAttribute("name");
	pattern.exec(type);
	var tail = (RegExp.$2) ? josa(eval(RegExp.$1),RegExp.$2) : "";
	
	//alert(type.replace(pattern,eval(RegExp.$1) + tail));
	var msg = type.replace(pattern,eval(RegExp.$1) + tail);
	if (msg!="") {
		msg = msg.charAt(0).toUpperCase() + msg.substr(1);
	}
	alert(msg);
	
	if (action == "sel") {
		el.select();
	} else if (action == "del")	{
		el.value = "";
	}
	el.focus();
	return false;
}	

/// 특수 패턴 검사 함수 매핑 ///
var funcs = new Array();
funcs['email'] = isValidEmail;
funcs['email_tr'] = isValidEmailtr;
funcs['phone'] = isValidPhone;
funcs['userid'] = isValidUserid;
funcs['nickname'] = isValidNickname;
funcs['password'] = isValidPassword;
funcs['hangul'] = hasHangul;
funcs['number'] = isNumeric;
funcs['engonly'] = alphaOnly;
funcs['jumin'] = isValidJumin;
funcs['bizno'] = isValidBizNo;
funcs['fileExtDoc'] = isDocFile;
funcs['fileExtImg'] = isImgFile;
funcs['date'] = isDate;

/// 패턴 검사 함수들 ///
function isValidEmail(el) {
	var pattern = /^[_a-zA-Z0-9-\.]+@[\.a-zA-Z0-9-]+\.[a-zA-Z]+$/;
//	var pattern = /^[a-z][\w.-]+@\w[\w.-]+\[\w.-]*[a-z][a-z]$/i;
//	var pattern = /(\w|[_.\-])+@((\w|-)+\.)+\w{2,4}+/;
	return (pattern.test(el.value)) ? true : doError(el,NOT_VALID_EMAIL);
}

function isValidEmailtr(el) {
	var pattern = /^[_a-zA-Z0-9-\.]+@[\.a-zA-Z0-9-]+\.[a-zA-Z]+$/;
	return (pattern.test(el.value)) ? true : retEmailTr(el);
}

function retEmailTr(el){
	alert(el.getAttribute("trname"));
	el.focus();
	return false;
}

function isValidUserid(el) {
	var pattern = /^[a-z0-9]{4,12}$/;	
   	return (pattern.test(el.value)) ? true : doError(el,"Your ID must be made up of lowercase letters and/or numbers. It may not contain capitals or symbols and must be at least 4~12 characters in length. Once your ID is registered, it cannot be changed.");
}

function isValidNickname(el) {
	var pattern = /^[a-zA-Z0-9]{4,12}$/;
	return (pattern.test(el.value)) ? true : doError(el,"Only use alphabets and numbers, at least 4~12 characters in length.");
}

/* 패스워드 형식 검증 */
function isValidPassword(el) {
	var pattern1 = /^[a-zA-Z0-9]{4,12}$/;
	var pattern2 = /[0-9]{1,}/;	
	var pattern3 = /[a-zA-Z]{1,}/;	
	return ( pattern1.test(el.value) && pattern2.test(el.value) && pattern3.test(el.value) ) ? true : doError(el, "Your password may include any combination of lowercase letters and/or numbers (no symbols or caps.) and must be at least 4-12 characters in length.");
}

function hasHangul(el) {
	var pattern = /[가-힝]/;
	return (pattern.test(el.value)) ? true : doError(el,"{name} must include Hanguel (Korean alphabet). ");
}

function alphaOnly(el) {
	var pattern = /^[a-zA-Z]+$/;
	return (pattern.test(el.value)) ? true : doError(el,NOT_VALID);
}

function isNumeric(el) {
	var pattern = /^[0-9]+$/;
	return (pattern.test(el.value)) ? true : doError(el,"{name} must be entered in numbers.");
}

function isValidJumin(el,value) {
    var pattern = /^([0-9]{6})-?([0-9]{7})$/; 
	var num = value ? value : el.value;
    if (!pattern.test(num)) return doError(el,NOT_VALID); 
    num = RegExp.$1 + RegExp.$2;

	var sum = 0;
	var last = num.charCodeAt(12) - 0x30;
	var bases = "234567892345";
	for (var i=0; i<12; i=i+1) {
		if (isNaN(num.substring(i,i+1))) return doError(el,NOT_VALID);
		sum += (num.charCodeAt(i) - 0x30) * (bases.charCodeAt(i) - 0x30);
	}
	var mod = sum % 11;
	return ((11 - mod) % 10 == last) ? true : doError(el,NOT_VALID);
}

function isValidBizNo(el) { 
    var pattern = /([0-9]{3})-?([0-9]{2})-?([0-9]{5})/; 
	var num = el.value;
    if (!pattern.test(num)) return doError(el,NOT_VALID); 
    num = RegExp.$1 + RegExp.$2 + RegExp.$3;
    var cVal = 0; 
    for (var i=0; i<8; i=i+1) { 
        var cKeyNum = parseInt(((_tmp = i % 3) == 0) ? 1 : ( _tmp  == 1 ) ? 3 : 7); 
        cVal += (parseFloat(num.substring(i,i+1)) * cKeyNum) % 10; 
    } 
    var li_temp = parseFloat(num.substring(i,i+1)) * 5 + '0'; 
    cVal += parseFloat(li_temp.substring(0,1)) + parseFloat(li_temp.substring(1,2)); 
    return (parseInt(num.substring(9,10)) == 10-(cVal % 10)%10) ? true : doError(el,NOT_VALID); 
}

function isValidPhone(el) {
    var pattern = /^[0-9\-]{7,20}$/;
	if (pattern.test(el.value)) {
		return true;
	} else {
		var usermsg = el.getAttribute("USERMSG");
		if (usermsg=="true") return doError(el,USER_MSG);
		else return doError(el,NOT_VALID);
	}
}

function isDocFile(el) 
{
	var extArray = ".doc";
	var file = el.value;

	allowSubmit = false;
	if(!file) {
		allowSubmit = false;
	}
	ext = file.slice(file.lastIndexOf (".")).toLowerCase();

	if (extArray == ext) { allowSubmit = true;}
	else {allowSubmit = false;}

	if(allowSubmit) {
		return true;
	} else {
		return doError(el,NOT_DOC);
	}

}

function isImgFile(el) 
{
	var file = el.value;

	allowSubmit = false;
	if(!file) {
		allowSubmit = false;
	}
	ext = file.slice(file.lastIndexOf (".")).toLowerCase();

	if (ext==".jpg" || ext==".jpeg" || ext==".gif") { allowSubmit = true;}
	else {allowSubmit = false;}

	if(allowSubmit) {
		return true;
	} else {
		return doError(el,NOT_IMG);
	}

}




function isDate(el) 
{
	var str = el.value;
	var strDate;
	var yy, mm, dd;
	if (isEmpty(str)){
		return false;
	} else {
	
		//숫자인지 체크
		if (!isNumeric(el)){
			el.focus();
			el.value = "";
			return false;
		}
		
		//에러처리length <4 
		if (str.length<4){
			el.value = "";
			return doError(el,"The year of {name} is incorrect.");
		}

		if (!isYear(str.substring(0,4))){
			el.value = "";
			return doError(el,"The year of {name} is incorrect.");
		}
		yy = str.substring(0,4);
		switch(str.length){
			case 4 :
				mm = "01";
				dd = "01";
				break;
			case 5 :
				if (!isMonth(str.charAt(4))){
					el.value = "";
					return doError(el,"The month of {name} is incorrect.");
				}
				mm = "0" + str.charAt(4);
				dd = "01";
				break;
			case 6 :
				if (!isMonth(str.substr(4,2))){
					if (!isDay(yy, "0"+str.charAt(4) , "0"+str.charAt(5))){
						el.value = "";
						return doError(el,"{name} is incorrect. Ex) 20071031");
					} else{
						mm = "0" + str.charAt(4);
						dd = "0" + str.charAt(5);
					}
				}
				else{
					mm = str.substr(4,2);
					dd = "01";
				}
				break;
			case 7 :
				if (!isMonth(str.substr(4,2))){
					alert(yy + "0" + str.charAt(4)+ str.substr(5,2));
					formName.focus();
					return;
					if (!isDay(yy , "0" + str.charAt(4), str.substr(5,2))){
						el.value = "";
						return doError(el,"The month or day of {name} is incorrect.");
					} else{
						mm = "0" + str.charAt(4);
						dd = str.substring(5);
					}
				} else {
					if (!isDay(yy, str.substr(4,2), + "0" + str.charAt(6))){
						el.value = "";
						return doError(el,"The date of {name} is incorrect.");
					}
					mm = str.substr(4,2);
					dd = "0" + str.charAt(6);
				}
				break;
			case 8 :
				if (!isDay(yy, str.substr(4,2), str.substring(6))){
					el.value = "";
					return doError(el,"The month or day of {name} is incorrect.");
				}
				mm = str.substr(4,2);
				dd = str.substring(6);
				break;
		}
		if (!isDate(yy + mm + dd)){
			el.value = "";
			return doError(el,"The format of {name} is incorrect.");
		}
		formName.value = yy + "-" + mm + "-" + dd;
	}
	
}


function isDateVal(val) 
{
	var str = val;
	var strDate;
	var yy, mm, dd;
	if (isEmpty(str)){
		return false;
		
	} else {
		
		//에러처리length <4 
		if (str.length<4){
			alert("The year is incorrect.");
			return false;
		}

		if (!isYear(str.substring(0,4))){
			alert("The year is incorrect.");
			return false;
		}
		yy = str.substring(0,4);
		switch(str.length){
			case 4 :
				mm = "01";
				dd = "01";
				break;
			case 5 :
				if (!isMonth(str.charAt(4))){
					alert("The month is incorect.");
					return false;
				}
				mm = "0" + str.charAt(4);
				dd = "01";
				break;
			case 6 :
				if (!isMonth(str.substr(4,2))){
					if (!isDay(yy, "0"+str.charAt(4) , "0"+str.charAt(5))){
						alert("The date is incorrect. Ex) 20071031");
						return false;
					} else{
						mm = "0" + str.charAt(4);
						dd = "0" + str.charAt(5);
					}
				}
				else{
					mm = str.substr(4,2);
					dd = "01";
				}
				break;
			case 7 :
				if (!isMonth(str.substr(4,2))){
					alert(yy + "0" + str.charAt(4)+ str.substr(5,2));
					return false;
					if (!isDay(yy , "0" + str.charAt(4), str.substr(5,2))){
						alert("The month or day is incorect.");
						return false;
					} else{
						mm = "0" + str.charAt(4);
						dd = str.substring(5);
					}
				} else {
					if (!isDay(yy, str.substr(4,2), + "0" + str.charAt(6))){
						alert("The date is incorrect.");
						return false;
					}
					mm = str.substr(4,2);
					dd = "0" + str.charAt(6);
				}
				break;
			case 8 :
				if (!isDay(yy, str.substr(4,2), str.substring(6))){
					alert("The month or day is incorect.");
					return false;
				}
				mm = str.substr(4,2);
				dd = str.substring(6);
				break;
		}
		
		return true;
		
	}
	
}


/** =============================================
Comment: 입력값(str)의 앞/뒤 공백을 제거한 후 길이가 0 이면 false
Return : boolean
Usage  : if (isEmpty(abc.value) ==true) return false;
--------------------------------------------- **/
function isEmpty(str) {
    return ( str == null || str.replace(/ /gi,"") == "" ? true : false);
}

/** =============================================
Comment: 입력값(str)이 숫자이면 true
Return : boolean
Usage  : isNumber(aaa.value)
--------------------------------------------- **/
function isNumber(arg) {
	var filtered_str = "";

	for(i=0;i<arg.length;i++)
	{
		if(arg.charAt(i) != ',')
			filtered_str = filtered_str + arg.charAt(i);
	}

	for(i=0;i<filtered_str.length;i++)
	{
		if((filtered_str.charAt(i) < '0') || (filtered_str.charAt(i) > '9'))
			return false;
	}
	return true;
}

/** =============================================
Comment: 입력값(str)이 년도이면 true
Return : boolean
Usage  : isYear(aaa.value)
--------------------------------------------- **/
function isYear(str) {
	var ny;
	
	if (!isNumber(str)) {
		return false;
	}
	
	if(str.length != 4) {
		return false;
	}
	
	ny = parseInt(str);

	if(!(isNumber(str))||(ny < 1000)||(ny > 9999))
		return false ;
	
	return true;
}


/** =============================================
Comment: 입력값(str)이 '월'형식이면 true
Return : boolean
Usage  : isMonth(aaa.value)
--------------------------------------------- **/
function isMonth(str) {
	var nm, mm;
	
	if (!isNumber(str)) {
		return false;
	}
	
	if (parseInt(str) < 10) {
		mm = str.substring(1);
	} else {
		mm = str;
	}
	
	if(str.length != 2) {
		str = "0" + str;
	}
	
	nm = parseInt(mm);

	if(!(isNumber(mm))||(nm < 1)||(nm > 12))
		return false ;
	
	return true;
}



/** =============================================
Comment: 입력값(year_str, month_str, day_str)이 각각 날짜형식이면 true
Return : boolean
Usage  : isDay(aaa.value, bbb.value, ccc.value)
--------------------------------------------- **/
function isDay(year_str, month_str, day_str) {
	var yy,mm,dd,ny,nm,nd;
	var arr_d;

	isYear(year_str);
	isMonth(month_str);
	
	if (!isNumber(day_str)) {
		return false;
	}
	
	if (day_str.length == 0) {
		return false;
	}
	
	if (day_str.length != 2) {
		day_str = "0" + day_str;
	}

	if (year_str.length + month_str.length + day_str.length != 8) {
		return false;
	}

	yy = year_str;
	mm = month_str;
	dd = day_str;

	if (mm < '10')
		mm = mm.substring(1) ;
	if (dd < '10')
		dd = dd.substring(1) ;

	ny = parseInt(yy);
	nm = parseInt(mm);
	nd = parseInt(dd);

	if(!(isNumber(yy))||(ny < 1000)||(ny > 9999))
		return false ;
	if(!(isNumber(mm))||(nm < 1)||(nm > 12))
		return false ;
	arr_d = new Array('31','28','31','30','31','30','31','31','30','31','30','31');
	
	if(((ny % 4 == 0)&&(ny % 100 != 0))||(ny % 400 == 0))
		arr_d[1] = 29;
	if(!(isNumber(dd))||(nd < 1)||(nd > arr_d[nm-1]))
		return false ;
	
	return true;
}
/**
 * 입력 컨트롤의 글자수 보여주는 유틸
 *
 **/
function fc_chk_byte(aro_name, ari_max, showctrl) {

	var ls_str = aro_name.value; // 이벤트가 일어난 컨트롤의 value 값
	var li_str_len = ls_str.length; // 전체길이

 	// 변수초기화
 	var li_max = ari_max; // 제한할 글자수 크기
 	var i = 0; // for문에 사용
 	var li_byte = 0; // 한글일경우는 2 그밗에는 1을 더함
 	var li_len = 0; // substring하기 위해서 사용
 	var ls_one_char = ""; // 한글자씩 검사한다
 	var ls_str2 = ""; // 글자수를 초과하면 제한할수 글자전까지만 보여준다.

  	for(i=0; i< li_str_len; i++) {
   		// 한글자추출
   		ls_one_char = ls_str.charAt(i);

   		// 한글이면 3를 더한다.
		if (escape(ls_one_char).length > 4) {
    		li_byte += 3;
   		}
   		// 그밗의 경우는 1을 더한다.
   		else {
    		li_byte++;
   		}

   		// 전체 크기가 li_max를 넘지않으면
   		if(li_byte <= li_max) {
    		li_len = i + 1;
   		}
  	}

  	// 전체길이를 초과하면
  	if(li_byte > li_max) {
   		alert( li_max + "You cannot exceed the specified number of characters. Exceeded characters are automatically deleted.");
   		ls_str2 = ls_str.substr(0, li_len);
   		aro_name.value = ls_str2;
  	}
  	else {
   		document.getElementById(showctrl).innerHTML = li_byte;
  	}
  	aro_name.focus(); 
}
