/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
// +--------------------------------------------------------+
// | Copyright (c) 2003-2004 Song Hyo-Jin                   |
// +--------------------------------------------------------+
// | Author : Song Hyo-Jin <crosser at hanmail dot net>     |
// |                                  (MSN Messengerable)   |
// +--------------------------------------------------------+
//
// Category : SHJ/js
// Package  : SHJ JavaScript
//
// $Id: validate.js, v 0.1.0 2007/11/08 0:20:00 crosser Exp $

function josaObj()
{
	this.tempDiv = document.createElement("P");
	this.tempDiv.innerHTML = "&#51008;&#45716;"; // 은는 //
	
	this.EunNun = this.tempDiv.innerHTML;
	
	this.tempDiv.innerHTML = "&#51060;&#44032;"; // 이가 //
	
	this.IeGa = this.tempDiv.innerHTML;
	
	this.entityAlert = function(message)
	{
		this.tempDiv.innerHTML = message;
		window.alert(this.tempDiv.innerHTML);
	}
	
	this.josa = function(str, tail)
	{
		var strTemp;
	
		strTemp = str.substr(str.length - 1);
		if(strTemp.charCodeAt(0) < 129) {
			pattern = /([aeiou][^aeiouwy]e|mb|ck|ng|l|m|n)$/i;
			return pattern.test(str) ? str + tail.substr(0, 1) : str + tail.substr(1, 1);
		}
	
		return ((strTemp.charCodeAt(0) - 16) % 28 != 0) ? str + tail.substr(0, 1) : str + tail.substr(1, 1);
	}
}

var josa = new josaObj();

function validator(obj_id, form_id)
{
	this.obj_id = obj_id;
	this.form = document.getElementById(form_id);
	this.targets = new Array();

	this.init = function() {
		this.form.validator = this;
	}

	this.check = function() {
		var i;
		for(i = 0; i < this.targets.length; i ++) {
			if(!this.targets[i].check()) {
				return false;
			}
		}
		if(this.lastconfirm) {
			return window.confirm(this.lastconfirm);
		}
		return true;
	}
	
	this.setChecker = function(name, index) {
		if(typeof(index) == 'undefined') {
			index = -1;
		}
		return this.targets[this.targets.length] = new checker((index == -1) ? this.form[name] : this.form[name][index], this.obj_id, this.targets.length);
	}
}

function checker(target, obj_id, length)
{
	var e, i, j, c;
	try {
		target[0].value;
		if(target[0].tagName == "OPTION") {
			this.target = new Array();
			this.target[0] = target;
		} else {
			this.target = target;
		}
	} catch(e) {
		this.target = new Array();
		this.target[0] = target;
	}
	
	this.set = function(checktype) {
		this.check_types = checktype.split(/\s*,\s*/);
		return this;
	}
	this.setValue = function(attribute, value) {
		this[attribute] = value;
		return this;
	}
	
	this.check = function() {
		for(c = 0; c < this.check_types.length; c ++) {
			for(i = 0; i < this.target.length; i ++) {
				switch(this.check_types[c]) {
					case 'int':
						this.target[i].value = this.target[i].value.toInt();
						break;
					case 'uint':
						this.target[i].value = this.target[i].value.toInt(true);
						break;
					case 'float':
						this.target[i].value = this.target[i].value.toFloat();
						break;
					case 'ufloat':
						this.target[i].value = this.target[i].value.toFloat(true);
						break;
					case 'lower':
						this.target[i].value = this.target[i].value.toLowerCase();
						break;
					case 'upper':
						this.target[i].value = this.target[i].value.toUpperCase();
						break;
					case 'alpha':
						this.target[i].value = this.target[i].value.toAlphabet();
						break;
					case 'alnum':
						this.target[i].value = this.target[i].value.toAlnum();
						break;
					case 'korean':
						this.target[i].value = this.target[i].value.toKorean();
						break;
					case 'allkorean':
						this.target[i].value = this.target[i].value.toAllKorean();
						break;
					case 'alnumkorean':
						this.target[i].value = this.target[i].value.toAlnumKorean();
						break;
					case 'trim':
						this.target[i].value = this.target[i].value.trim();
						break;
					case 'ltrim':
						this.target[i].value = this.target[i].value.lTrim();
						break;
					case 'rtrim':
						this.target[i].value = this.target[i].value.rTrim();
						break;
					case 'denyspace':
						this.target[i].value = this.target[i].value.denySpace();
						break;
					case 'denyblank':
						if(this.target[i].value == "") {
							josa.entityAlert(josa.josa(this.target[i].title, josa.EunNun) + " 꼭 채우셔야 합니다.");
							this.target[i].focus();
							return false;
						}
						break;
					case 'limitmin':
						if(this.target[i].value.toInt(true) < this.limitMin * 1) {
							this.target[i].value = this.limitMin;
						}
						break;
					case 'limitmax':
						if(this.target[i].value.toInt(true) > this.limitMax * 1) {
							this.target[i].value = this.limitMax;
						}
						break;
					case 'limitminlen':
						if(this.target[i].value.length < this.limitMinLen * 1) {
							josa.entityAlert(josa.josa(this.target[i].title, josa.EunNun) + " " + this.limitMinLen + "글자 이상 적으셔야 합니다.");
							this.target[i].focus();
							return false;
						}
						break;
					case 'limitmaxlen':
						if(this.target[i].value.length > this.limitMaxLen * 1) {
							this.target[i].value = this.target[i].value.substr(0, this.limitMaxLen * 1);
						}
						break;
					case 'limitmincheck':
						var checkboxes = 0;
						if(this.target[0].name.substr(this.target[0].name.length - 2) == "[]") {
							if(!!this.target[0].form[this.target[0].name].checked) {
								checkboxes ++;
							} else {
								for(j = 0; j < this.target[0].form[this.target[0].name].length; j ++) {
									if(this.target[0].form[this.target[0].name][j].checked) {
										checkboxes ++;
									}
								}
							}
							if(checkboxes < this.limitMinCheck * 1) {
								josa.entityAlert(josa.josa(this.target[0].title, josa.EunNun) + " " + this.limitMinCheck + "가지 이상으로 체크하셔야 합니다.");
								this.target[0].focus();
								return false;
							}
							i = this.target[0].form[this.target[0].name].length;
						} else {
							if(!this.target[0].checked) {
								josa.entityAlert(josa.josa(this.target[0].title, josa.EunNun) + " 반드시 체크하셔야 합니다.");
								this.target[0].focus();
								return false;
							}
						}
						break;
					case 'limitmaxcheck':
						var checkboxes = 0;
						if(!!this.target[0].form[this.target[0].name].checked) {
							checkboxes ++;
						} else {
							for(j = 0; j < this.target[0].form[this.target[0].name].length; j ++) {
								if(this.target[0].form[this.target[0].name][j].checked) {
									checkboxes ++;
								}
							}
						}
						if(checkboxes > this.limitMaxCheck * 1) {
							josa.entityAlert(josa.josa(this.target[0].title, josa.EunNun) + " " + this.limitMaxCheck + "가지 이하로 체크하셔야 합니다.");
							this.target[0].focus();
							return false;
						}
						i = this.target[0].form[this.target[0].name].length;
						break;
					case 'personalnumber':
						if(i == 0) continue;
						var personal_number = this.target[0].value.denySpace() + this.target[1].value.denySpace();
						if(!checkPersonalNumber(personal_number) && personal_number != "") {
							josa.entityAlert(josa.josa(this.target[0].title, josa.IeGa) + " 잘못되었습니다.");
							this.target[0].focus();
							return false;
						}
						break;
					case 'password':
						if(i == 0) continue;
						if(this.target[0].value != this.target[1].value) {
							josa.entityAlert(josa.josa(this.target[0].title, josa.IeGa) + " 서로 맞지 않습니다.");
							this.target[0].focus();
							return false;
						}
						break;
					case 'email':
						if(!checkEmail(this.target[i].value) && this.target[i].value != "") {
							josa.entityAlert(this.target[i].title + "의 형식이 맞지 않습니다.");
							this.target[i].focus();
							return false;
						}
						break;
					case 'tel':
						if(i < 2) continue;
						var number = this.target[0].value + this.target[1].value + this.target[2].value;
						if(!checkTel(number, 1) && number != "") {
							josa.entityAlert(josa.josa(this.target[0].title, josa.IeGa) + " 잘못되었습니다.");
							this.target[0].focus();
							return false;
						}
						break;
					case 'cell':
						if(i < 2) continue;
						var number = this.target[0].value + this.target[1].value + this.target[2].value;
						if(!checkTel(number, 2) && number != "") {
							josa.entityAlert(josa.josa(this.target[0].title, josa.IeGa) + " 잘못되었습니다.");
							this.target[0].focus();
							return false;
						}
						break;
					case 'alltel':
						if(i < 2) continue;
						var number = this.target[0].value + this.target[1].value + this.target[2].value;
						if(!checkTel(number, 3) && number != "") {
							josa.entityAlert(josa.josa(this.target[0].title, josa.IeGa) + " 잘못되었습니다.");
							this.target[0].focus();
							return false;
						}
						break;
					default:
						josa.entityAlert("알 수 없는 옵션 " + this.check_types[c]);
						return false;
						break;
				}
			}
		}
		return true;
	}
}

function checkPersonalNumber(personal_number)
{
	var pattern = /^[0-9]{6}[1-4][0-9]{6}$/;
	if(!pattern.test(personal_number)) {
		return false;
	}
	var month = personal_number.substr(2, 2) * 1;
	var day = personal_number.substr(4, 2) * 1;

	if(month < 1 || month > 12) {
		return false;
	}
	if(day < 1 || day > 31) {
		return false;
	}
	var check = 0;
	var mul = 2;

	for(i = 0; i < 12; i ++) {
		check += personal_number.charAt(i) * mul;
		mul ++;
		if(mul > 9) {
			mul = 2;
		}
	}

	check = 11 - (check % 11);

	if(check > 9) {
		check %= 10;
	}
	if(check != personal_number.charAt(12)) {
		return false;
	}
	return true;
}

function checkEmail(emailtext)
{
	var pattern = /^[_a-z0-9\-\.]{1,255}@[\.a-z0-9\-]{2,255}\.(com|net|org|af|al|dz|as|ad|ao|ai|aq|ag|ar|am|aw|au|at|az|bs|bh|bd|bb|by|be|bz|bj|bm|bt|bo|ba|bw|bv|br|io|vg|bn|bg|bf|bi|kh|cm|ca|cv|ky|cf|td|cl|cn|cx|cc|co|km|cd|cg|ck|cr|ci|cu|cy|cz|dk|dj|dm|do|ec|eg|sv|gq|er|ee|et|fo|fk|fj|fi|fr|gf|pf|tf|ga|gm|ge|de|gh|gi|gr|gl|gd|gp|gu|gt|gn|gw|gy|ht|hm|va|hn|hk|hr|hu|is|in|id|ir|iq|ie|il|it|jm|jp|jo|kz|ke|ki|kp|kr|kw|kg|la|lv|lb|ls|lr|ly|li|lt|lu|mo|mk|mg|mw|my|mv|ml|mt|mh|mq|mr|mu|yt|mx|fm|md|mc|mn|ms|ma|mz|mm|na|nr|np|an|nl|nc|nz|ni|ne|ng|nu|nf|mp|no|om|pk|pw|ps|pa|pg|py|pe|ph|pn|pl|pt|pr|qa|re|ro|ru|rw|sh|kn|lc|pm|vc|ws|sm|st|sa|sn|cs|sc|sl|sg|sk|si|sb|so|za|gs|es|lk|sd|sr|sj|sz|se|ch|sy|tw|tj|tz|th|tl|tg|tk|to|tt|tn|tr|tm|tc|tv|vi|ug|ua|ae|gb|um|us|uy|uz|vu|ve|vn|wf|eh|ye|zm|zw)$/;
	if(!pattern.test(emailtext)) {
		return false;
	}
	return true;
}

function checkTel(number, type)
{
	var tel_pattern = /^0(2|3[1-3]|4[1-3]|5[1-5]|6[1-4])([2-9][0-9]{2}|[1-9][0-9]{3})[0-9]{4}$/;
	var cell_pattern = /^01[016789][1-9][0-9]{2,3}[0-9]{4}$/;
	switch(type) {
		case 1:
			if(!tel_pattern.test(number)) {
				return false;
			}
			break;
		case 2:
			if(!cell_pattern.test(number)) {
				return false;
			}
			break;
		case 3:
			if(!tel_pattern.test(number) && !cell_pattern.test(number)) {
				return false;
			}
			break;
	}
	return true;
}


// 라디오버튼 선택 : 이름, 순서 //
function radioOne(rname, ord)
{
	var r;

	r = document.getElementsByName(rname);
	r[ord].checked = true;

	return true;
}

// 체크박스 다중선택 : 이름, 바이너리플래그 //
function checkAll(cbname, bin)
{
	var flag = 1,
		i = 0,
		cb;

	cb = document.getElementsByName(cbname);

	while(bin >= flag) {
		if(bin & flag) {
			cb[i].checked = true;
		}

		flag <<= 1;
		i ++;
	}

	return true;
}

// 체크박스 전체토글 : 이름, 부울 //
function checkUnified(cbname, flag)
{
	var i, cb;
	cb = document.getElementsByName(cbname);
	
	for(i = 0; i < cb.length; i ++) {
		cb[i].checked = flag;
	}
	
	return true;
}

// 체크박스 다중선택 폼 국한 : 폼ID, 이름, 바이너리플래그 //
function checkAllByForm(frmname, cbname, bin)
{
	var flag = 1,
		i = 0,
		j = 0,
		frm,
		inp,
		cb;

	cb = new Object();

	frm = document.getElementById(frmname);
	inp = frm.getElementsByTagName('INPUT');
	for(i = 0; i < inp.length; i ++) {
		if(inp[i].name == cbname) {
			cb[j] = inp[i];
			j ++;
		}
	}
	//cb = frm.getElementsByName(cbname);

	i = 0;
	while(bin >= flag) {
		if(bin & flag) {
			cb[i].checked = true;
		}

		flag <<= 1;
		i ++;
	}

	return true;
}


// 셀렉트 선택 : 이름, 값 //
function selectOne(sname, val)
{
	var s, i, j;

	s = document.getElementsByName(sname);
	for(i = 0; i < s.length; i ++) {
		for(j = 0; j < s[i].options.length; j ++) {
			if(s[i].options[j].value == val) {
				s[i].options[j].selected = true;
			}
		}
	}

	return true;
}

// 셀렉트 다중선택 : 이름, 바이너리플래그 //
function selectAll(sname, bin)
{
	var flag = 1,
		i = 0,
		s;

	s = document.getElementsByName(sname);

	while(bin >= flag) {
		if(bin & flag) {
			s[0].options[i].selected = true;
		}

		flag <<= 1;
		i ++;
	}

	return true;
}
