/**
* 입력폼 폼검증을 하기 위한 프레임워크
* TLE.js 수정
* version 1.1
*
* 수정 이력
* 2008.06.17 폼검증시 입력폼에 공백만 입력할 경우 trim 적용 function validatorTrim(str)
* 2008.06.17 폼검증시 공백일 경우 focus이동시 text 필드 초기화  
* 2009.05.21 폼검증시 alert형태가 아닌 <div> or <span> 에 message 보여줄수 있도록 수정
* 수정자 김상진(jabsiri@enz.co.kr)
**/

function FormChecker(checkForm) {
	this.checkForm = checkForm;
	this.validatorList = new Array();
}

/**
* 공백문자를 제거하기 위한 함수 
**/
function validatorTrim(str) {
	return str.replace(/^\s+|\s+$/g,"");
}

/*
// 화이트스페이스 존재 여부 검사
function isWhiteSpace(str){
	var pattern = /\s+/;
	if(str.length == 0 ){
		return true;
	}
	return (pattern.test(str) && str.length == RegExp.lastIndex) ? true : false;
}

// 공백과 엔터 모두 공백으로 치환
function replaceWhitespace(str) {
	while(str.indexOf(" ") != -1 || str.indexOf("\n") != -1 || str.indexOf("\r") != -1 ) {
		str = str.replace(" ","");
		str = str.replace("\n","");
		str = str.replace("\r","");
	}
	return str;
}
*/


/* 
 * 입력필드에 값이 없는지 체크
 * @param jsonObject {fieldName:"검사필드명", errorField:"alert말고 page에 출력할 영역 id", errorMessage:"에러 메시지", isFocus:true,false} 
 */
FormChecker.prototype.checkRequired = function(jsonObject) {
	this.validatorList.push(new RequiredValidator(this.checkForm, jsonObject));
}
/*
 * 최대 길이값 체크
 * @ fieldName 필드 명
 * @ maxLength 최대 길이값
 * @ errorMessage alert을 통해 사용자에게 보여줄 메시지
 * @ focus 체크 결과에 해당할경우 alert이후 fieldName에 포커스 줄지 여부
 */
FormChecker.prototype.checkMaxLength = function(jsonObject) {
	this.validatorList.push(new MaxLengthValidator(this.checkForm, jsonObject));
}


/*
 * 최대 바이트값 체크
 * @ fieldName 필드 명
 * @ maxLength 최대 바이트 값
 * @ errorMessage alert을 통해 사용자에게 보여줄 메시지
 * @ focus 체크 결과에 해당할경우 alert이후 fieldName에 포커스 줄지 여부
 */
FormChecker.prototype.checkMaxLengthByte = function(jsonObject) {
	this.validatorList.push(new MaxLengthByteValidator(this.checkForm, jsonObject));
}

FormChecker.prototype.checkMinLength = function(jsonObject) {
	this.validatorList.push(new MinLengthValidator(this.checkForm, jsonObject));
}

FormChecker.prototype.checkMinNumber = function(jsonObject) {
	this.validatorList.push(new MinNumberValidator(this.checkForm, jsonObject));
}

/*
 * 최소 바이트값 체크
 * @ fieldName 필드 명
 * @ minLength 최소 바이트 값
 * @ errorMessage alert을 통해 사용자에게 보여줄 메시지
 * @ focus 체크 결과에 해당할경우 alert이후 fieldName에 포커스 줄지 여부
*/
FormChecker.prototype.checkMinLengthByte = function(jsonObject) {
	this.validatorList.push(new MinLengthByteValidator(this.checkForm, jsonObject));
}

FormChecker.prototype.checkRegex = function(jsonObject) {
	this.validatorList.push(
		new RegexValidator(this.checkForm, jsonObject));
}
/*
* 영문과 숫자만 있는지 체크
*/
FormChecker.prototype.checkAlphaNum = function( jsonObject ) {
	jsonObject.regex = /^[a-zA-Z0-9]+$/; 
	this.validatorList.push(new RegexValidator(this.checkForm, jsonObject));
}

/*
* 오직 숫자만 있는지 체크
*/
FormChecker.prototype.checkOnlyNumber = function(jsonObject) {
	jsonObject.regex = /^[0-9]+$/; 
	this.validatorList.push(new RegexValidator(this.checkForm, jsonObject));
}
/*
* 오직 영문만 있는지 체크
*/
FormChecker.prototype.checkOnlyAlpha = function(jsonObject) {
	jsonObject.regex = /^[a-zA-Z]+$/;
	this.validatorList.push(new RegexValidator(this.checkForm, jsonObject)); 
}

/*
* 오직 영문과 숫자만 있는지 체크
*/
FormChecker.prototype.checkOnlyAlphaNumAndBar = function(jsonObject) {
	jsonObject.regex = /^[a-zA-Z0-9_-]+$/;
	this.validatorList.push(new RegexValidator(this.checkForm, jsonObject));
}

/*
*
*/
FormChecker.prototype.checkDecimal = function(jsonObject) {
	jsonObject.regex = /^(\-)?[0-9]*(\.[0-9]*)?$/;
	this.validatorList.push( new RegexValidator(this.checkForm, jsonObject) );
}
/*
* 이메일 형식 체크
*/
FormChecker.prototype.checkEmail = function(jsonObject) {
	jsonObject.regex = /^((\w|[\-\.])+)@((\w|[\-\.])+)\.([A-Za-z]+)$/;
	this.validatorList.push(new RegexValidator(this.checkForm, jsonObject) );
}

FormChecker.prototype.checkUrl = function(jsonObject) {
	jsonObject.regex = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
	this.validatorList.push( new RegexValidator(this.checkForm, jsonObject) );
}

/*
* SELECT 값 체크
*/
FormChecker.prototype.checkSelected = function(jsonObject) {
	this.validatorList.push(new SelectionValidator(this.checkForm, jsonObject));
}

/*
* CHECK BOX 값체크 
*/
FormChecker.prototype.checkAtLeastOneChecked = function(jsonObject) {
	this.validatorList.push(new AtLeastOneCheckValidator(this.checkForm, jsonObject));
}
/*
* selectbox 에세의 오류로 인해 주석처리 수정 요망
FormChecker.prototype.validate = function() {
	for (vali = 0 ; vali < this.validatorList.length ; vali ++ ) {
		validator = this.validatorList[vali];
		if (validator.validate() == false) {
			alert(validator.getErrorMessage());
			if (validator.isFocus() == true) {
				exe = this.checkForm[validator.getFieldName()];					
					alert(this.checkForm[validator.getFieldName()][0].type.toLowerCase());				
				if(exe.length != 'undefined' && exe.length > 1){
					if( this.checkForm[validator.getFieldName()][0].type.toLowerCase() == 'text'
						|| this.checkForm[validator.getFieldName()][0].type.toLowerCase() == 'textarea'){
						this.checkForm[validator.getFieldName()].value = '';
					}			 
					this.checkForm[validator.getFieldName()][0].focus();
				}else{	
					if( this.checkForm[validator.getFieldName()].type.toLowerCase() == 'text'
						|| this.checkForm[validator.getFieldName()].type.toLowerCase() == 'textarea'){
						this.checkForm[validator.getFieldName()].value = '';
					}			 
					this.checkForm[validator.getFieldName()].focus();
				}
			}
			return false;
		}
	}
	return true;
}*/

FormChecker.prototype.validate = function() {
	for (vali = 0 ; vali < this.validatorList.length ; vali ++ ) {
		validator = this.validatorList[vali];
		if (validator.validate() == false) {
			alert(validator.getErrorMessage());
			if (validator.isFocus() == true) {
				this.checkForm[validator.getFieldName()].focus();
			}
			return false;
		}
	}
	return true;
}

FormChecker.prototype.validateInnerHTML = function(isOneMessage) {
	var result = true;
	var errorMessage = {};
	
	for (vali = 0 ; vali < this.validatorList.length ; vali ++ ) {
		validator = this.validatorList[vali];
		
		if (validator.validate() == false) {
			
			//alert(errorMessage[validator.getErrorField()]);
			
			if( errorMessage[validator.getErrorField()] == "" || typeof errorMessage[validator.getErrorField()] == 'undefined' ){
				document.getElementById(validator.getErrorField()).innerHTML = validator.getErrorMessage();
				errorMessage[validator.getErrorField()] = true;
			}
			
			if (validator.isFocus() == true) {
				if( result ) {	 
					this.checkForm[validator.getFieldName()].focus();
				}
			}
			
			if( isOneMessage ){
				return false;
			}
			
			result = false;
		}else{
			if( errorMessage[validator.getErrorField()] == "" || typeof errorMessage[validator.getErrorField()] == 'undefined' ){
				document.getElementById(validator.getErrorField()).innerHTML = "";
			}
		}
	}
	return result;
}



FormChecker.prototype.getForm = function() {
	return this.checkForm;
}


// Validator is base class of all validators
function Vaildator() {
}
Vaildator.prototype.getFieldName = function() {
	return this.jsonObject.fieldName;
}
Vaildator.prototype.getErrorField = function() {
	return this.jsonObject.errorField;
}
Vaildator.prototype.getErrorMessage = function() {
	return this.jsonObject.errorMessage;
}
Vaildator.prototype.isFocus = function() {
	return this.jsonObject.isFocus;
}

// required validator
function RequiredValidator(form, jsonObject) {
	this.form = form;
	this.jsonObject = jsonObject;
	//this.fieldName = fieldName;
	//this.errorMessage = errorMessage;
	//this.focus = focus;
	//this.isErrorField = isErrorField;
}
RequiredValidator.prototype = new Vaildator;
RequiredValidator.prototype.validate = function() {
	return validatorTrim(this.form[this.jsonObject.fieldName].value) != '';
}

// max length validator
function MaxLengthValidator(form, jsonObject) {
	this.form = form;
	this.jsonObject = jsonObject;
	//this.fieldName = fieldName;
	//this.errorMessage = errorMessage;
	//this.focus = focus;
	//this.maxLength = maxLength;
}
MaxLengthValidator.prototype = new Vaildator;
MaxLengthValidator.prototype.validate = function() {
	return this.form[this.jsonObject.fieldName].value.length <= this.jsonObject.maxLength;
}

// max length(byte) validator
function MaxLengthByteValidator(form, jsonObject) {
	this.form = form;
	this.jsonObject = jsonObject;
	/*
	this.fieldName = fieldName;
	this.errorMessage = errorMessage;
	this.focus = focus;
	this.maxLength = maxLength;
	*/
}
MaxLengthByteValidator.prototype = new Vaildator;
MaxLengthByteValidator.prototype.validate = function() {
	str = this.form[this.jsonObject.fieldName].value;
	return(str.length+(escape(str)+"%u").match(/%u/g).length-1) <= this.jsonObject.maxLength;
}

// min length validator
function MinLengthValidator(form, jsonObject) {
	this.form = form;
	this.jsonObject = jsonObject;
	/*
	this.fieldName = fieldName;
	this.errorMessage = errorMessage;
	this.focus = focus;
	this.minLength = minLength;
	*/
}
MinLengthValidator.prototype = new Vaildator;
MinLengthValidator.prototype.validate = function() {
	return this.form[this.jsonObject.fieldName].value.length >= this.jsonObject.minLength;
}

//min length validator
function MinNumberValidator(form, jsonObject) {
	this.form = form;
	this.jsonObject = jsonObject;
}
MinNumberValidator.prototype = new Vaildator;
MinNumberValidator.prototype.validate = function() {
	var result = false;
	try {
		result = Number(this.form[this.jsonObject.fieldName].value) >= Number(this.jsonObject.minNumber);
	}catch(e){
		alert(e);
	}
	return result;
}



// min length(byte) validator
function MinLengthByteValidator(form, jsonObject) {
	this.form = form;
	this.jsonObject = jsonObject;
	/*
	this.fieldName = fieldName;
	this.errorMessage = errorMessage;
	this.focus = focus;
	this.minLength = minLength;
	*/
}
MinLengthByteValidator.prototype = new Vaildator;
MinLengthByteValidator.prototype.validate = function() {
	str = this.form[this.jsonObject.fieldName].value;
	return(str.length+(escape(str)+"%u").match(/%u/g).length-1) >= this.jsonObject.minLength;
}

// regex pattern validator
function RegexValidator(form, jsonObject) {
	this.form = form;
	this.jsonObject = jsonObject;
	//this.regex = regex;
	//this.errorMessage = errorMessage;
	//this.focus = focus;
	//this.isErrorField = isErrorField;
}
RegexValidator.prototype = new Vaildator;
RegexValidator.prototype.validate = function() {
	var str = this.form[this.jsonObject.fieldName].value;
	if (str.length == 0) return true;
	return str.search(this.jsonObject.regex) != -1;
}

// check selected
function SelectionValidator(form, jsonObject) {
	this.form = form;
	this.jsonObject = jsonObject;
	/*
	this.fieldName = fieldName;
	this.firstIdx = firstIdx;
	this.errorMessage = errorMessage;
	this.focus = focus;
	*/
}
SelectionValidator.prototype = new Vaildator;
SelectionValidator.prototype.validate = function() {
	var idx = this.form[this.jsonObject.fieldName].selectedIndex;
	return idx >= this.jsonObject.firstIdx;
}

// check checkbox checked
function AtLeastOneCheckValidator(form, jsonObject) {
	this.form = form;
	this.jsonObject = jsonObject;
	/*
	this.fieldName = fieldName;
	this.errorMessage = errorMessage;
	this.focus = focus;
	*/
}
AtLeastOneCheckValidator.prototype = new Vaildator;
AtLeastOneCheckValidator.prototype.validate = function() {
	ele = this.form[this.jsonObject.fieldName];
	if (typeof(ele[0]) != "undefined") {
		// 2~
		for (var idxe = 0 ; idxe < ele.length ; idxe++) {
			if (ele[idxe].checked == true) {
				return true;
			}
		}
		return false;
	} else {
		// only 1
		return ele.checked == true;
	}
}

