var fvalidator = function(form) {
    this.form = fvalidator.getFormElement(form);
    if (!this.form) return false;

    this.conditions = [];
    this.groupConditions = [];
    this.errorCondition = null;
    this.errorGroupCondition = null;
    this.errorType = null;
};

fvalidator.FORMAT_MAP = {
    email      : "fFormat.email",
    hangul     : "fFormat.hangul",
    engonly    : "fFormat.engonly",
    number     : "fFormat.number",
    residentno : "fFormat.residentno",
    jumin      : "fFormat.jumin",
    foreignerno: "fFormat.foreignerno",
    bizno      : "fFormat.bizno",
    phone      : "fFormat.phone",
    homephone  : "fFormat.homephone",
    handphone  : "fFormat.handphone",
    isdate     : "fFormat.isdate",
    zip        : "fFormat.zip",
    jurino     : "fFormat.jurino"
};

fvalidator.ERROR_MESSAGE_PATTERN = "[{label}] {message}";

fvalidator.ERROR_MESSAGE = {
    /* for element */
    required   : "¹Ýµå½Ã ÀÔ·ÂÇÏ¼Å¾ß ÇÏ´Â »çÇ×ÀÔ´Ï´Ù.",
    requiredstring : "¹Ýµå½Ã {required}(À¸)·Î ÀÔ·ÂÇÏ¼Å¾ß ÇÏ´Â »çÇ×ÀÔ´Ï´Ù.",
    match      : "ÀÔ·ÂµÈ ³»¿ëÀÌ ÀÏÄ¡ÇÏÁö ¾Ê½À´Ï´Ù.",
    invalid    : "ÀÔ·ÂµÈ ³»¿ëÀÌ ¿Ã¹Ù¸£Áö ¾Ê½À´Ï´Ù.",
    min        : "{min} ÀÌ»óÀÇ °ªÀ» ÀÔ·ÂÇØÁÖ¼¼¿ä.",
    max        : "{max} ÀÌÇÏÀÇ °ªÀ» ÀÔ·ÂÇØÁÖ¼¼¿ä.",
    minlength  : "ÀÔ·ÂµÈ ³»¿ëÀÌ {minlength}±ÛÀÚ ÀÌ»óÀÌ¾î¾ß ÇÕ´Ï´Ù.",
    minbyte    : "ÀÔ·ÂµÈ ³»¿ëÀÇ ±æÀÌ°¡ {minbyte}Byte ÀÌ»óÀÌ¾î¾ß ÇÕ´Ï´Ù.",
    maxbyte    : "ÀÔ·ÂµÈ ³»¿ëÀÇ ±æÀÌ°¡ {maxbyte}Byte¸¦ ÃÊ°úÇÒ ¼ö ¾ø½À´Ï´Ù.",
    mincheck   : "{mincheck}°³ÀÇ Ç×¸ñ ÀÌ»óÀ¸·Î ¼±ÅÃÇÏ¼¼¿ä.",
    maxcheck   : "{maxcheck}°³ÀÇ Ç×¸ñ ÀÌÇÏ·Î ¼±ÅÃÇÏ¼¼¿ä.",
    minselect  : "{minselect}°³ÀÇ Ç×¸ñ ÀÌ»óÀ¸·Î ¼±ÅÃÇÏ¼¼¿ä.",
    maxselect  : "{maxselect}°³ÀÇ Ç×¸ñ ÀÌÇÏ·Î ¼±ÅÃÇÏ¼¼¿ä.",
    imageonly  : "ÀÌ¹ÌÁö ÆÄÀÏ¸¸ Ã·ºÎ ÇÒ ¼ö ÀÖ½À´Ï´Ù.",
    fileonly   : "{fileonly} Çü½ÄÀÇ ÆÄÀÏ¸¸ Ã·ºÎ ÇÒ ¼ö ÀÖ½À´Ï´Ù.",

    /* for group */
    requiremin : "{requiremin}°³ ÀÌ»óÀÇ Ç×¸ñÀÌ ÀÔ·ÂµÇ¾î¾ß ÇÕ´Ï´Ù.",
    requiremax : "{requiremax}°³ ÀÌÇÏÀÇ Ç×¸ñÀÌ ÀÔ·ÂµÇ¾î¾ß ÇÕ´Ï´Ù.",

    /* for format */
    email      : "ÀÌ¸ÞÀÏ Çü½ÄÀÌ ¿Ã¹Ù¸£Áö ¾Ê½À´Ï´Ù.",
    hangul     : "¹Ýµå½Ã ÇÑ±Û·Î ÀÔ·ÂÇÏ¼Å¾ß ÇÕ´Ï´Ù.",
    engonly    : "¿µ¹®À¸·Î¸¸ ÀÔ·ÂÇÏ¼Å¾ß ÇÕ´Ï´Ù.",
    number     : "¼ýÀÚ·Î¸¸ ÀÔ·ÂÇÏ¼Å¾ß ÇÕ´Ï´Ù.",
    residentno : "ÁÖ¹Îµî·Ï¹øÈ£ Çü½ÄÀÌ ¿Ã¹Ù¸£Áö ¾Ê½À´Ï´Ù.",
    jumin      : "ÁÖ¹Îµî·Ï¹øÈ£ Çü½ÄÀÌ ¿Ã¹Ù¸£Áö ¾Ê½À´Ï´Ù.",
    foreignerno: "¿Ü±¹ÀÎµî·Ï¹øÈ£ Çü½ÄÀÌ ¿Ã¹Ù¸£Áö ¾Ê½À´Ï´Ù.",
    bizno      : "»ç¾÷ÀÚµî·Ï¹øÈ£ Çü½ÄÀÌ ¿Ã¹Ù¸£Áö ¾Ê½À´Ï´Ù.",
    phone      : "ÀüÈ­¹øÈ£ Çü½ÄÀÌ ¿Ã¹Ù¸£Áö ¾Ê½À´Ï´Ù.",
    homephone  : "À¯¼± ÀüÈ­¹øÈ£ Çü½ÄÀÌ ¿Ã¹Ù¸£Áö ¾Ê½À´Ï´Ù.",
    handphone  : "ÇÚµåÆù¹øÈ£ Çü½ÄÀÌ ¿Ã¹Ù¸£Áö ¾Ê½À´Ï´Ù.",
    isdate     : "³¯Â¥ Çü½ÄÀÌ ¿Ã¹Ù¸£Áö ¾Ê½À´Ï´Ù.",
    zip        : "¿ìÆí¹øÈ£ Çü½ÄÀÌ ¿Ã¹Ù¸£Áö ¾Ê½À´Ï´Ù.",
    jurino     : "¹ýÀÎ¹øÈ£ Çü½ÄÀÌ ¿Ã¹Ù¸£Áö ¾Ê½À´Ï´Ù."
};

fvalidator.TEXT = 1;
fvalidator.SELECT = 2;
fvalidator.MULTI_SELECT = 3;
fvalidator.CHECK = 4;
fvalidator.RADIO = 5;
fvalidator.FILE = 6;
fvalidator.HIDDEN = 7;

fvalidator.prototype.add = function(targetElement, targetOptions, targetLabel) {
    var condition = new fCondition(targetElement, targetOptions, targetLabel, this.form);

    if (condition)
        var newIndex = this.addCondition(condition);

    return newIndex ? newIndex : false;
};

fvalidator.prototype.addCondition = function(condition) {
    var newIndex = this.conditions.length;

    if (condition) {
        this.conditions[newIndex] = condition;
        return newIndex;
    } else {
        return false;
    };
};

fvalidator.prototype.addGroup = function(targetConditions, targetOptions, targetLabel) {
    var groupCondition = new fGroupCondition(targetConditions, targetOptions, targetLabel);

    if (groupCondition)
        var newIndex = this.addGroupCondition(groupCondition);

    return newIndex ? newIndex : false;
};

fvalidator.prototype.addGroupCondition = function(groupCondition){
    var newIndex = this.groupConditions.length;

    if (groupCondition) {
        this.groupConditions[newIndex] = groupCondition;
        return newIndex;
    } else {
        return false;
    };
};

fvalidator.prototype.validate = function() {
    var isFailed = false;

    // validate conditions
    for (var i=0, l=this.conditions.length; i < l; i++) {
        isFailed = !this.validateCondition(this.conditions[i]);
        if (isFailed) return false;
    };

    // validate group conditions
    for (var i=0, l=this.groupConditions.length; i < l; i++) {
        isFailed = !this.validateGroup(this.groupConditions[i]);
        if (isFailed) return false;
    };

    return true;
};

fvalidator.prototype.validateGroup = function(groupCondition) {
    var conditions = groupCondition.conditions;
    var optionsObj = groupCondition.optionsObj;

    var requiremin = optionsObj.requiremin ? parseInt(optionsObj.requiremin, 10) : 0;
    if (requiremin > 0) {
        var countValid = 0;
        var firstInvalidCondition = null;
        for (var i=0, l=conditions.length; i < l; i++) {
            if (this.validateCondition(conditions[i])) {
                countValid++;
                if (countValid >= requiremin)
                    break;
            } else {
                if (!firstInvalidCondition) {
                    firstInvalidCondition = conditions[i];
                };
                // if error type isn't `required`, raise Condition's Error
                if (this.errorType != "required") {
                    return false; // validationCondition method already raised Error.
                };
            };
        };
        if (countValid < requiremin)
            return this.raiseGroupError(groupCondition, firstInvalidCondition, "requiremin");
    };

    var requiremax = optionsObj.requiremax ? parseInt(optionsObj.requiremax, 10) : 0;
    if (requiremax > 0) {
        var countValid = 0;
        var firstInvalidCondition = null;
        for (var i=0, l=conditions.length; i < l; i++) {
            if (this.validateCondition(conditions[i])) {
                countValid++;
                if (countValid >= requiremax)
                    break;
            } else {
                if (!firstInvalidCondition) {
                    firstInvalidCondition = conditions[i];
                };
                // if error type isn't `required`, raise Condition's Error
                if (this.errorType != "required") {
                    return false; // validationCondition method already raised Error.
                };
            };
        };
        if (countValid < requiremax)
            return this.raiseGroupError(groupCondition, firstInvalidCondition, "requiremax");
    };

    return true;
};

fvalidator.prototype.validateCondition = function(condition) {
    var element = condition.element;
    var optionsObj = condition.optionsObj;
    var value = fvalidator.getValue(element);

    if (!fvalidator.isActiveFormControl(element)) return true; // ignore

    var type = fvalidator.getElementType(element);
    if (!type) return true; // ignore

    var useifvalid = optionsObj.useifvalid || null;
    var useifinvalid = optionsObj.useifinvalid || null;
    if (useifvalid) {
        if (!this.validateCondition(useifvalid))
            return true; // regard as valid
    };
    if (useifinvalid) {
        if (this.validateCondition(useifvalid))
            return true; // regard as valid
    };

    var isEmpty = fvalidator.isEmptyElement(element, type);

    var trim = optionsObj.trim || null;
    if (trim) {
        if (type == fvalidator.TEXT || type == fvalidator.HIDDEN) {
            switch (trim) {
                case true: case "trim":
                    value = value.replace(/^\s+/, "").replace(/\s+$/, "");
                    break;
                case "compress":
                    value = value.replace(/\s+/g, "");
                    break;
                case "ltrim":
                    value = value.replace(/^\s+/, "");
                    break;
                case "rtrim":
                    value = value.replace(/\s+$/, "");
                    break;
            };
        };
        if (value == "" && !isEmpty) isEmpty = true;
    };

    var required = optionsObj.required || null;
    if (required && isEmpty) {
        return this.raiseError(condition, "required");
    } else if (typeof required == "string" && required != value) {
        return this.raiseError(condition, "requiredstring");
    };

    var min = parseInt(optionsObj.min, 10) || null;
    var max = parseInt(optionsObj.max, 10) || null;
    if ((min != null || max != null) && !isEmpty) {
        if (type == fvalidator.TEXT || type == fvalidator.HIDDEN) {
            var isNumber = /^[0-9]*$/.test(value);
            if (!isNumber)
                return this.raiseError(condition, "number");
            var intValue = parseInt(value, 10);
            if (min != null && intValue < min)
                return this.raiseError(condition, "min");
            if (max != null && intValue > max)
                return this.raiseError(condition, "max");
        };
    };

    var minlength = parseInt(optionsObj.minlength, 10) || null;
    if (minlength > 0 && !isEmpty) {
        if (type == fvalidator.TEXT || type == fvalidator.HIDDEN) {
            if (value.length < minlength)
                return this.raiseError(condition, "minlength");
        };
    };

    var minbyte = parseInt(optionsObj.minbyte, 10) || null;
    var maxbyte = parseInt(optionsObj.maxbyte, 10) || null;
    if ((minbyte > 0 || maxbyte > 0) && !isEmpty) {
        if (type == fvalidator.TEXT || type == fvalidator.HIDDEN) {
            var valueByte = value.length;
            for (i=0, l=value.length; i < l; i++) {
                if (value.charCodeAt(i) > 128)
                    valueByte++;
            };
            if (minbyte > 0 && valueByte < minbyte)
                return this.raiseError(condition, "minbyte");
            if (maxbyte > 0 && valueByte > maxbyte)
                return this.raiseError(condition, "maxbyte");
        };
    };

    var match = optionsObj.match || null;
    if (match) {
        if (type != fvalidator.FILE) {
            var matchElement = fvalidator.getElement(match, this.form);
            if (matchElement && value != fvalidator.getValue(matchElement))
                return this.raiseError(condition, "match");
        };
    };

    var option = optionsObj.option || null;
    if (option && !isEmpty) {
        if (type != fvalidator.FILE && fvalidator.FORMAT_MAP[option]) {
            var formatFunction = eval(fvalidator.FORMAT_MAP[option]);
            var formatResult;
            var span = parseInt(optionsObj.span, 10) || null;
            var glue = optionsObj.glue || "";

            var _options = option.split(/\s/);
            for (var i=0, l=_options.length; i < l; i++) {
                var format = fvalidator.FORMAT_MAP[_options[i]];

                if (span && typeof value != "object") {
                    var spanedValue = value;
                    var _elementForSpan = element;
                    for (var j = 1; j < span; j++) {
                        _elementForSpan = fvalidator.getNextElement(_elementForSpan);
                        if (_elementForSpan) {
                            if (typeof glue == "object" && glue.length + 1 == span) {
                                spanedValue += glue[j-1] + fvalidator.getValue(_elementForSpan);
                            } else {
                                spanedValue += glue + fvalidator.getValue(_elementForSpan);
                            }
                        };
                    };
                    formatResult = formatFunction(element, spanedValue);
                } else {
                    formatResult = formatFunction(element, value);
                };
                if (typeof formatResult == "string")
                    return this.raiseError(condition, formatResult);
            };
        };
    };

    var pattern = optionsObj.pattern || null;
    if (pattern && !isEmpty) {
        if (type != fvalidator.FILE) {
            patternRegExp = new RegExp(pattern);
            if (typeof value == "object") {
                for (var i=0; i<value.length; i++) {
                    if (!patternRegExp.test(value[i])) {
                        return this.raiseError(condition, "invalid");
                    };
                };
            } else if (!patternRegExp.test(value)) {
                return this.raiseError(condition, "invalid");
            };
        };
    };

    var mincheck = parseInt(optionsObj.mincheck, 10) || null;
    var maxcheck = parseInt(optionsObj.maxcheck, 10) || null;
    if (mincheck > 0 || maxcheck > 0) {
        if (type == fvalidator.CHECK) {
            if (mincheck > 0 && value.length < mincheck)
                return this.raiseError(condition, "mincheck");
            if (maxcheck > 0 && value.length > maxcheck)
                return this.raiseError(condition, "maxcheck");
        };
    };

    var minselect = parseInt(optionsObj.minselect, 10) || null;
    var maxselect = parseInt(optionsObj.maxselect, 10) || null;
    if (minselect > 0 || maxselect > 0) {
        if (type == fvalidator.MULTI_SELECT) {
            if (minselect > 0 && value.length < minselect)
                return this.raiseError(condition, "minselect");
            if (maxselect > 0 && value.length > maxselect)
                return this.raiseError(condition, "maxselect");
        };
    };

    var imageonly = optionsObj.imageonly || null;
    if (imageonly && !isEmpty) {
        if (type == fvalidator.FILE) {
            var dotIndex = value.lastIndexOf(".");
            var ext = value.substr(dotIndex + 1).toLowerCase();
            if(ext != "jpg" && ext != "jpeg" && ext != "gif" && ext != "png")
                return this.raiseError(condition, "imageonly");
        };
    };

    var fileonly = optionsObj.fileonly || null;
    if (fileonly && !isEmpty) {
        if (type == fvalidator.FILE) {
            var dotIndex = value.lastIndexOf(".");
            var ext = value.substr(dotIndex + 1).toLowerCase();

			var isValidFile = false;
			for (var i=0, l=fileonly.length; i < l; i++) {
				if (ext == fileonly[i].toLowerCase()) {
					isValidFile = true;
					break;
				};
			};

			if (!isValidFile) {
				return this.raiseError(condition, "fileonly");
			};
        };
    };

    return true;
};
/**
 * set information of invalid condition
 * @param fCondition condition
 * @param string errorType - key of optionsObj (required, match, and so on...)
 * @return false
 */
fvalidator.prototype.raiseError = function(condition, errorType) {
    this.errorCondition = condition;
    this.errorType = errorType;

    return false;
};
/**
 * set information of invalid group condition
 * @param fGroupCondition groupCondition
 * @param fCondition firstInvalidCondition
 * @param string errorType - key of optionsObj (requiremin, requiremax, ...)
 * @return false
 */
fvalidator.prototype.raiseGroupError = function(groupCondition, firstInvalidCondition, errorType) {
    this.errorGroupCondition = groupCondition;
    this.errorCondition = firstInvalidCondition;
    this.errorType = errorType;

    return false;
};
/**
 * get first invalid element what fvalidator detected
 */
fvalidator.prototype.getErrorElement = function() {
    return this.errorCondition ? this.errorCondition.element : null;
};
/**
 * get error message with errorMessagePattern, when errorMessagePattern is null, default pattern is used.
 * @param string errorMessagePattern
 * @return string
 */
fvalidator.prototype.getErrorMessage = function(errorMessagePattern) {
    if (!this.errorCondition || !this.errorType)
        return null;

    if (this.errorGroupCondition) {
        var optionsObj = this.errorGroupCondition.optionsObj;
        var label = this.errorGroupCondition.label;
    } else {
        var optionsObj = this.errorCondition.optionsObj;
        var label = this.errorCondition.label;
    };
    var typeMessage = fvalidator.ERROR_MESSAGE[this.errorType] || this.errorType;
    var message = optionsObj.message || typeMessage;

    var dynamicPattern = /\{([a-z0-9_]+)\}/i;
    if (dynamicPattern.test(message) == true) {
        while (dynamicPattern.exec(message)) {
            if (RegExp.$1 && optionsObj[RegExp.$1]) {
                var optionTxt = optionsObj[RegExp.$1];
                if (optionTxt.constructor &&
                        optionTxt.constructor.toString().indexOf("Array") > -1) {
                    optionTxt = optionTxt.join(", ");
                };
                message = message.replace(dynamicPattern, optionTxt);
            } else {
                break;
            };
        };
    };

    var messagePattern = errorMessagePattern
                            ? errorMessagePattern
                            : fvalidator.ERROR_MESSAGE_PATTERN;
    var errorMessage = messagePattern.replace(/{label}/, label);
    var errorMessage = errorMessage.replace(/{message}/, message);
    return errorMessage;
};
/**
 * check element is active form control
 * @param DOM Element element
 * @return boolean - true if element is active form control
 * @static
 */
fvalidator.isActiveFormControl = function(element) {
    return element.tagName
            && element.tagName.match(/^input|select|textarea$/i)
            && !element.disabled;
};
/**
 * check element's value is empty
 * @param DOM Element element
 * @return boolean - true if element is empty
 * @static
 */
fvalidator.isEmptyElement = function(element) {
    var value = fvalidator.getValue(element);
    return !value;
};
/**
 * get DOM Element of form
 * @param mixed form - can be DOM Element, id attribute or name attribute.
 * @return DOM Element or false
 */
fvalidator.getFormElement = function(form) {
    if (form.tagName)
        return form;
    else if (document.getElementById
            && document.getElementById(form))
        return document.getElementById(form);
    else if (document.forms
            && document.forms[form])
        return document.forms[form];
    else
        return false;
};
/**
 * get DOM Element of form control
 * @param mixed element - can be DOM Element, id attribute or name attribute.
                          if name attribute presented, elementForm is required.
 * @param DOM Element elementForm
 * @return DOM Element or false
 * @static
 */
fvalidator.getElement = function(element, elementForm) {
    if (element.tagName) {
        return element;
    } else if (elementForm && elementForm.elements && elementForm.elements[element]) {
        if (!elementForm.elements[element].tagName
                && elementForm.elements[element].length)
            return elementForm.elements[element][0];
        else
            return elementForm.elements[element];
    } else if (document.getElementById
            && document.getElementById(element)) {
        return document.getElementById(element);
    } else {
        return false;
    };
};
/**
 * get type of form control
 * @param DOM Element element
 * @return number or false
 */
fvalidator.getElementType = function(element) {
    if (!element.tagName) return false;

    var tagName = element.tagName.toLowerCase();
    var type = element.type;
    var multiple = element.multiple;

    if (tagName == "textarea" ||
            (tagName == "input" && (type == "text" || type == "password")))
        return fvalidator.TEXT;
    else if (tagName == "select" && multiple)
        return fvalidator.MULTI_SELECT;
    else if (tagName == "select")
        return fvalidator.SELECT;
    else if (tagName == "input" && type == "checkbox")
        return fvalidator.CHECK;
    else if (tagName == "input" && type == "radio")
        return fvalidator.RADIO;
    else if (tagName == "input" && type == "file")
        return fvalidator.FILE;
    else if (tagName == "input" && type == "hidden")
        return fvalidator.HIDDEN;
    else
        return false;
};
/**
 * get value of form control
 * @param DOM Element element
 * @return string
 */
fvalidator.getValue = function(element) {
    var type = fvalidator.getElementType(element);

    switch (type) {
        case fvalidator.TEXT:
        case fvalidator.HIDDEN:
        case fvalidator.FILE:
            return element.value;
            break;
        case fvalidator.SELECT:
            for (var i=0, l=element.options.length; i<l; i++) {
                if (element.options[i].selected) {
                    return element.options[i].value;
                };
            };
            break;
        case fvalidator.MULTI_SELECT:
            var values = [];
            for (var i=0, l=element.options.length; i<l; i++) {
                if (element.options[i].selected) {
                    values[values.length] = element.options[i].value;
                };
            };
            return values.length > 0 ? values : null;
            break;
        case fvalidator.CHECK:
            if (element.form && element.name) {
                var checkElements = element.form.elements[element.name];
                var values = [];
                if (checkElements.length) {
                    for (var i=0, l=checkElements.length; i<l; i++) {
                        if (checkElements[i].checked == true)
                            values[values.length] = checkElements[i].value;
                    };
                } else {
                    if (checkElements.checked == true)
                        values[values.length] = checkElements.value;
                };
                return values.length > 0 ? values : null;
            };
            break;
        case fvalidator.RADIO:
            if (element.form && element.name) {
                var checkElements = element.form.elements[element.name];
                if (checkElements.length) {
                    for (var i=0, l=checkElements.length; i<l; i++) {
                        if (checkElements[i].checked == true)
                            return checkElements[i].value;
                    };
                } else {
                    if (checkElements.checked == true)
                        return checkElements.value;
                };
            };
            break;
    };
    return null;
};
/**
 * get next form control of form control
 * @param DOM Element element
 * @return DOM Element or null
 */
fvalidator.getNextElement = function(element) {
    if (element.form) {
        var form = element.form;
        for (var i=0, l=form.elements.length; i<l; i++) {
            if (form.elements[i] == element) {
                var count = i;
                while (++count < form.elements.length
                        && fvalidator.isActiveFormControl(form.elements[count])) {
                    return form.elements[count];
                };
            };
        };
    } else if (element.nextSibling) {
        var _nextElement = element;
        while (_nextElement = element.nextSibling) {
            if (fvalidator.isActiveFormControl(_nextElement))
                return _nextElement;
        };
    };
    return null;
};

/**
 * constructor
 * @param mixed targetElement - can be DOM Element, id attribute or name attribute of form control.
                                if name attribute presented, targetForm is required.
 * @param Object targetOptions - validation options of form control
 * @param string targetLabel - label of form control. if not presented,
 *                             fCondition try to find label from HTML Document
 * @param DOM Element targetForm
 * @return void
 */
var fCondition = function(targetElement, targetOptions, targetLabel, targetForm) {
    var element = fvalidator.getElement(targetElement, targetForm);

    if (!fvalidator.isActiveFormControl(element)) return false;

    this.element = element;
    this.optionsObj = targetOptions || {};
    this.label = targetLabel || fCondition.getHTMLLabel(element);
};
/**
 * add new option, overwrite if option exist.
 * @param string key
 * @param mixed val
 * @return void
 */
fCondition.prototype.addOption = function(key, val) {
    this.optionsObj[key] = val;
};
/**
 * remove exist option.
 * @param string key
 * @return void
 */
fCondition.prototype.removeOption = function(key) {
    this.optionsObj[key] = null;
};
/**
 * get option with key
 * @param string key
 * @return mixed(value of option) or null
 */
fCondition.prototype.getOption = function(key) {
    return this.optionsObj[key] ? this.optionsObj[key] : null;
};
/**
 * detect label of form control from HTML Document. if no label find, return "noname"
 * @param DOM Element element
 * @return string
 * @static
 */
fCondition.getHTMLLabel = function(element) {
    var currentLabel = "";
    if (document.getElementsByTagName) {
        var currentLabelElement;
        labelLoop:
        for (var i=0, l=document.getElementsByTagName("label").length; i<l; i++) {
            var labelElement = document.getElementsByTagName("label")[i];
            var labelChilds = labelElement.childNodes;

            if (labelElement.htmlFor && labelElement.htmlFor == element.id) {
                currentLabelElement = labelElement;
                break labelLoop;
            };
            for (var _i=0, _l=labelChilds.length; _i<_l; _i++) {
                if (labelChilds[_i] == element) {
                    currentLabelElement = labelElement;
                    break labelLoop;
                };
            };
        };
        if (currentLabelElement) {
            var labelChilds = currentLabelElement.childNodes;
            for (var i=0, l=labelChilds.length; i<l; i++) {
                if (!labelChilds[i].tagName) // check is text node
                    currentLabel += labelChilds[i].nodeValue.replace(/^\s+/, "").replace(/\s+$/, "");
            };
        };
    };
    if (!currentLabel) {
        if (element.title)
            currentLabel = element.title;
        else if (element.id)
            currentLabel = element.id;
        else if (element.name)
            currentLabel = element.name;
        else
            currentLabel = "noname";
    };
    return currentLabel;
};

/**
 * constructor
 * @param Array targetConditions - items of array must be fCondition instance
 * @param Object targetOptions - validation options of group condition
 * @param string targetLabel - label for group condition. if not presented,
                               labels of targetConditions is used.
 * @return void
 */
var fGroupCondition = function(targetConditions, targetOptions, targetLabel) {
    this.conditions = targetConditions || [];
    this.optionsObj = targetOptions || {};
    if (targetLabel) {
        this.label = targetLabel;
    } else {
        this.label = "";
        for (var i=0, l=this.conditions.length; i < l; i++) {
            this.label += this.label ? ", " : "";
            this.label += this.conditions[i].label;
        };
    };
};
/**
 * add new condition
 * @param {Object} condition
 * @return number - index of condition Array
 */
fGroupCondition.prototype.addCondition = function(condition) {
    var index = this.conditions.length;
    this.conditions[index] = condition;
    return index;
};
/**
 * get condition
 * @param number index - index of condition Array
 * @return fCondition or null
 */
fGroupCondition.prototype.getCondition = function(index) {
    return this.conditions[index] ? this.conditions[index] : null;
};
/**
 * remove exist condition
 * @param number index - index of condition Array
 * @return void
 */
fGroupCondition.prototype.removeCondition = function(index) {
    var len = this.conditions.length;
    if (this.conditions[index]) {
        var flag = false;
        for (var i=0; i<len; i++) {
            if (i == index)
                flag = true;

            if (flag == true && i+1 < len) {
                this.conditions[i] = this.conditions[i+1];
            };
        };
        this.conditions.length = len - 1;
    };
};

var fFormat = {};
fFormat.email = function(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 : "email";
};
fFormat.hangul = function(el,value) {
    var value = value ? value : el.value;
    var pattern = /^[°¡-ÆR]+$/;
    return pattern.test(value) ? true : "hangul";
};
fFormat.engonly = function(el,value) {
    var value = value ? value : el.value;
    var pattern = /^[a-zA-Z]+$/;
    return pattern.test(value) ? true : "engonly";
};
fFormat.number = function(el,value) {
    var value = value ? value : el.value;
    var pattern = /^[0-9]+$/;
    return pattern.test(value) ? true : "number";
};
fFormat.residentno = function(el,value) {
    var pattern = /^(\d{6})-?(\d{5}(\d{1})\d{1})$/;
    var num = value ? value : el.value;
    if (!pattern.test(num)) return "invalid";
    num = RegExp.$1 + RegExp.$2;
    if (RegExp.$3 == 7 || RegExp.$3 == 8 || RegExp.$4 == 9)
        if ((num[7]*10 + num[8]) %2) return "residentno";

    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 "residentno";
        sum += (num.charCodeAt(i) - 0x30) * (bases.charCodeAt(i) - 0x30);
    };
    var mod = sum % 11;
    if(RegExp.$3 == 7 || RegExp.$3 == 8 || RegExp.$4 == 9)
        return (11 - mod + 2) % 10 == last ? true : "residentno";
    else
        return (11 - mod) % 10 == last ? true : "residentno";
};
fFormat.jumin = function(el,value) {
    var pattern = /^([0-9]{6})-?([0-9]{7})$/;
    var num = value ? value : el.value;
    if (!pattern.test(num)) return "jumin";
    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 "jumin";
        sum += (num.charCodeAt(i) - 0x30) * (bases.charCodeAt(i) - 0x30);
    };
    var mod = sum % 11;
    return (11 - mod) % 10 == last ? true : "jumin";
};
fFormat.foreignerno = function(el,value) {
    var pattern = /^(\d{6})-?(\d{5}[7-9]\d{1})$/;
    var num = value ? value : el.value;
    if (!pattern.test(num)) return "foreignerno";
    num = RegExp.$1 + RegExp.$2;
    if ((num[7]*10 + num[8]) %2) return "foreignerno";

    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 "foreignerno";
        sum += (num.charCodeAt(i) - 0x30) * (bases.charCodeAt(i) - 0x30);
    };
    var mod = sum % 11;
    return (11 - mod + 2) % 10 == last ? true : "foreignerno";
};
fFormat.bizno = function(el,value) {
    var pattern = /([0-9]{3})-?([0-9]{2})-?([0-9]{5})/;
    var num = value ? value : el.value;
    if (!pattern.test(num)) return "bizno";
    num = RegExp.$1 + RegExp.$2 + RegExp.$3;
    var cVal = 0;
    for (var i=0; i<8; i++) {
        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 : "bizno";
};
fFormat.phone = function(el,value) {
    var pattern = /^(0[2-8][0-5]?|01[01346-9])-?([1-9]{1}[0-9]{2,3})-?([0-9]{4})$/;
    var pattern15xx = /^(1544|1566|1577|1588|1644|1688)-?([0-9]{4})$/;
    var num = value ? value : el.value;
    return pattern.test(num) || pattern15xx.test(num) ? true : "phone";
};
fFormat.homephone = function(el,value) {
    var pattern = /^(0[2-8][0-5]?)-?([1-9]{1}[0-9]{2,3})-?([0-9]{4})$/;
    var pattern15xx = /^(1544|1566|1577|1588|1644|1688)-?([0-9]{4})$/;
    var num = value ? value : el.value;
    return pattern.test(num) || pattern15xx.test(num) ? true : "homephone";
};
fFormat.handphone = function(el,value) {
    var pattern = /^(01[01346-9])-?([1-9]{1}[0-9]{2,3})-?([0-9]{4})$/;
    var num = value ? value : el.value;
    return pattern.test(num) ? true : "handphone";
};
fFormat.isdate = function(el,value) {
    var value = value ? value : el.value;
    var pattern = /^[12][0-9]{3}\-[01]?[0-9]\-[0-3]?[0-9]$/;
    return pattern.test(value) ? true : "isdate";
};
fFormat.zip = function(el,value) {
    var value = value ? value : el.value;
    var pattern = /^[0-9]{3}\-[0-9]{3}$/;
    return pattern.test(value) ? true : "zip";
};
fFormat.jurino = function(el,value) {
    var num = value ? value : el.value;
    var pattern = /^([0-9]{6})-?([0-9]{7})$/;
    if (!pattern.test(num)) return "jurino";
    num = RegExp.$1 + RegExp.$2;
    var sum = 0;
    var last = parseInt(num.charAt(12), 10);
	for (var i=0; i<12; i++) {
		if (i % 2 == 0) {  // * 1
			sum += parseInt(num.charAt(i), 10);
		} else {    // * 2
			sum += parseInt(num.charAt(i), 10) * 2;
		};
	};
    var mod = sum % 10;
    return (10 - mod) % 10 == last ? true : "jurino";
};

/**
* direct_javascript function
*/

// È­¸éÁß¾Ó¿¡¼­ Ã¢¿­±â
function nwindow(page,name,w,h,scroll,resize){
var win= null;
  var winl = (screen.width-w)/2;
  var wint = (screen.height-h)/3;
  var settings  ='height='+h+',';
      settings +='width='+w+',';
      settings +='top='+wint+',';
      settings +='left='+winl+',';
      settings +='scrollbars='+scroll+',';
      settings +='resizable='+resize+',';
      settings +='status=no';
  win=window.open(page,name,settings);
  if(parseInt(navigator.appVersion) >= 4){win.window.focus();}
}
//¼ö·® ´õÇÏ±â
function num_plus(num){
	gnum = parseInt(num.value);
	num.value = gnum + 1;
	return;
}
//¼ö·® »©±â
function num_minus(num){
	gnum = parseInt(num.value);
	if( gnum > 0 ){
		num.value = gnum - 1;
	}
	return;
}
/**
 *  text ±âº»°ª
 * <input type="text" name="txtname"  value="default_value" onFocus="txt_default_value('focus', this, 'default_value');" onBlur="txt_default_value('blur', this, 'default_value');">
 */
function txt_default_value(mode, txtObj, default_val)
{
    if (mode == "focus" && txtObj.value == default_val) {
        txtObj.value = '';
    } else if (mode == "blur" && !txtObj.value) {
        txtObj.value = default_val;
    }
}

/**
 *  ¼ýÀÚ¸¸ ÀÔ·Â¹Þ´Â´Ù.
 *
 *  »ç¿ë¹ý : onKeyDown='onlyNumber()'
 *  ¼³ ¸í :  ÇÑ±ÛÀÔ·Â¾ÈµÊ. ¿£ÅÍ¿Í ¹é½ºÆäÀÌ½º,ÅÇÅ°,½ºÆäÀÌ½ºÅ°
 *           delete,insert,home/end/¹æÇâÅ°°ª,±×·¹ÀÌÅ°¼ýÀÚ°ª,Å°º¸µåÀ§¼ýÀÚ°ª¸¸ ÀÔ·Â°¡´ÉÇÏ´Ù.
 */

function onlyNumber() {
  if((event.keyCode<48) || (event.keyCode>57)){
    event.returnValue=false;
  }
}
function onlyEngnum() {
if ((event.keyCode <= 12592) || (event.keyCode >= 12687))
  event.returnValue = false;
}
function onlyNumDot() {
  if((event.keyCode<48) || (event.keyCode>57)){
    if(event.keyCode != 110) event.returnValue=false;
  }
}
/**
 *  ÇÑ±Û¸¸ ÀÔ·Â¹Þ´Â´Ù.
 *
 *  »ç¿ë¹ý : onKeyDown='onlyHangle()'
 */
function onlyHangle()
{
    var ek = event.keyCode
    if( ek != 13 && ek != 9 && ek != 8 && ek != 32 && ek != 46 && ek != 45 && ((ek < 48) ||(ek > 57)) )
     event.returnValue=false;
}

/**
 *  ¼ýÀÚ¿¡¼­ 3ÀÚ¸®¸¶´Ù ÄÄ¸¶ ºÙÀÌ±â
 *
 *  »ç¿ë¹ý : onKeyUp="numberformat(this)"
 *  ¼³ ¸í :  'onlyNumber()' °ú °°ÀÌ »ç¿ëÇÑ´Ù.
 */
function numberformat(obj)
{
    var num         = "";
    var only_num     = String(obj.value);
    only_num        = only_num.replace(/,|\s+/g, "");

    var len         = only_num.length;
    var pos         = len % 3;

    if (len < 3) {
        obj.value = only_num;
    } else {
        if (pos > 0) {
            num = only_num.substring(0,pos) + ",";
            len -= pos;
        }
        while (len > 3) {
            num += only_num.substring(pos, pos+3) + ",";
            len -= 3;
            pos += 3;
        }
        num += only_num.substring(pos, pos+3);
        obj.value = num;
    }
}

// ÀÚ¸®¼ö³Ñ±â¸é ´ÙÀ½
function move_field(argform,nextfield,chars,currfield) {
  var f = eval('document.'+ argform);
  var x= eval('document.' + argform + '.' +  currfield + '.' + 'value.length;');
  if (x == chars) {
    eval('document.' + argform + '.' + nextfield + '.focus();');
  }
}

/**
 *  ±Ý¾×ÀÔ·Â(3ÀÚ¸®¸¶´Ù ÄÄ¸¶ ºÙÀÌ±â), ÀÔ·ÂµÈ ±Ý¾× ÇÑ±Û·Î Ç¥½Ã
 *
 *  »ç¿ë¹ý : onKeyUp="numberformat(this)"
 *  <input type="text" name="A_EMONEY" size=18 maxLength=15 style="text-align:right"
 *	onkeypress="NUM_HAN(this.value,3,document.form.EMONEY_HAN)"
 *  onkeyup="this.value=numchk(this.value);
 *  NUM_HAN(this.value,3,document.form.EMONEY_HAN)"> ¿ø
 *  <input type="text" name="EMONEY_HAN" readonly style="border:0;" size="50">
 */

//ÄÞ¸¶ Âï±â
function commaStr( num ){
	var len,point,str;
	num = num+"";
	point = num.length%3
	len = num.length;

	str = num.substring(0,point);
	while( point < len){
		if( str != "" ) str += ",";
			str += num.substring( point , point+3);
			point +=3;
		}
	return str;
}

//±Ý¾×¿¡ , Âï±â
function numchk(num){
    num=new String(num);
    num=num.replace(/,/gi,"");
    return numchk1(num);
}

function numchk1(num){
    var sign="";
    if(isNaN(num)) {
        alert("¼ýÀÚ¸¸ ÀÔ·ÂÇÒ ¼ö ÀÖ½À´Ï´Ù.");
        return 0;
    }
    if(num==0) {
        return num;
    }

    if(num<0){
        num=num*(-1);
        sign="-";
    }
    else{
        num=num*1;
    }
    num = new String(num)
    var temp="";
    var pos=3;
    num_len=num.length;
    while (num_len>0){
        num_len=num_len-pos;
        if(num_len<0) {
            pos=num_len+pos;
            num_len=0;
        }
        temp=","+num.substr(num_len,pos)+temp;
    }
    return sign+temp.substr(1);
}

// ±Ý¾× ¼ýÀÚ¸¦ ÇÑ±Û·Î
function num_han(num)
{
    if ( num == "1" )       return "ÀÏ";
    else if ( num == "2" )  return "ÀÌ";
    else if ( num == "3" )  return "»ï";
    else if ( num == "4" )  return "»ç";
    else if ( num == "5" )  return "¿À";
    else if ( num == "6" )  return "À°";
    else if ( num == "7" )  return "Ä¥";
    else if ( num == "8" )  return "ÆÈ";
    else if ( num == "9" )  return "±¸";
    else if ( num == "½Ê" ) return "½Ê";
    else if ( num == "¹é" ) return "¹é";
    else if ( num == "Ãµ" ) return "Ãµ";
    else if ( num == "¸¸" ) return "¸¸ ";
    else if ( num == "¾ï" ) return "¾ï ";
    else if ( num == "Á¶" ) return "Á¶ ";
    else if ( num == "0" )  return "";
}

function NUM_HAN(num,mode,return_input)
{
    if ( num == "" || num == "0" ) {
        if ( mode == "3" ) {
            return_input.value = "";
        }
        return;
    }

    num=new String(num);
    num=num.replace(/,/gi,"");

    var len  = num.length;
    var temp1 = "";
    var temp2 = "";

    if ( len/4 > 3 && len/4 <= 4 ) {
        if ( len%4 == 0 ) {
            temp1 = ciphers_han(num.substring(0,4)) + "Á¶"
			+ ciphers_han(num.substring(4,8)) + "¾ï"
			+ ciphers_han(num.substring(8,12)) + "¸¸"
			+ ciphers_han(num.substring(12,16));
        }
        else {
            temp1 = ciphers_han(num.substring(0,len%4)) + "Á¶"
			+ ciphers_han(num.substring(len%4,len%4+4)) + "¾ï"
			+ ciphers_han(num.substring(len%4+4,len%4+8)) + "¸¸"
			+ ciphers_han(num.substring(len%4+8,len%4+12));
        }
    }
    else if ( len/4 > 2 && len/4 <= 3 ) {
        if ( len%4 == 0 ) {
            temp1 = ciphers_han(num.substring(0,4)) + "¾ï"
			+ ciphers_han(num.substring(4,8)) + "¸¸"
			+ ciphers_han(num.substring(8,12));
        }
        else {
            temp1 = ciphers_han(num.substring(0,len%4)) + "¾ï"
			+ ciphers_han(num.substring(len%4,len%4+4)) + "¸¸"
			+ ciphers_han(num.substring(len%4+4,len%4+8));
        }
    }
    else if ( len/4 > 1 && len/4 <= 2 ) {
        if ( len%4 == 0 ) {
            temp1 = ciphers_han(num.substring(0,4)) + "¸¸"
			+ ciphers_han(num.substring(4,len));
        }
        else {
            temp1 = ciphers_han(num.substring(0,len%4)) + "¸¸"
			+ ciphers_han(num.substring(len%4,len));
        }
    }
    else if ( len/4 <= 1 ) {
        temp1 = ciphers_han(num.substring(0,len));
    }

    for (var i=0; i<temp1.length; i++) {
        temp2 = temp2 + num_han(temp1.substring(i, i+1));
    }

    temp3=new String(temp2);
    temp3=temp3.replace(/¾ï ¸¸/gi,"¾ï ");
    temp3=temp3.replace(/Á¶ ¾ï/gi,"Á¶ ");

    if ( mode == 1 ) {
        alert(temp3 + " ¿ø");
    } else if ( mode == 2 ) {
        return temp3;
    } else if ( mode == 3 ) {
        return_input.value = "( " + temp3 + " ¿ø )";
    }
}

function ciphers_han(num)
{
    var len  = num.length;
    var temp = "";

    if ( len == 1 ) {
        temp = num;
    }
    else if ( len == 2 ) {
        temp = num.substring(0,1) + "½Ê"
		+ num.substring(1,2);
    }
    else if ( len == 3 ) {
        temp = num.substring(0,1) + "¹é"
		+ num.substring(1,2) + "½Ê"
		+ num.substring(2,3);
    }
    else if ( len == 4 ) {
        temp = num.substring(0,1) + "Ãµ"
		+ num.substring(1,2) + "¹é"
		+ num.substring(2,3) + "½Ê"
		+ num.substring(3,4);
    }

    num=new String(temp);
    num=num.replace(/0½Ê/gi,"");
    num=num.replace(/0¹é/gi,"");
    num=num.replace(/0Ãµ/gi,"");
    return num;
}
// ÅØ½ºÆ®¹Ú½º¿¡ value °ª³Ö±â
function Change (target,type)
{
       if ( target.value == target.defaultValue && type==0)
        {
           target.style.backgroundImage='';
           target.value = '';
        }
       if ( !target.value && type==1) target.value = target.defaultValue;
}
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}
// ¿ìÆí¹øÈ£
function s_zip(url){
 if(url) {
  nwindow(""+url+"/common/post.php?form=write&zip1=s_zip1&zip2=s_zip2&address=s_addr1", 'szipcode', '510' , '400' ,'yes','yes');
  } else {
  nwindow('/comm/post.php?form=write&zip1=s_zip1&zip2=s_zip2&address=s_addr1', 'szipcode', '510' , '400' ,'yes','yes');
  }
}
function e_zip(url){
 if(url) {
  nwindow(""+url+"/common/common/post.php?form=write&zip1=e_zip1&zip2=e_zip2&address=e_addr1", 'ezipcode', '510' , '400' ,'yes','yes');
  } else {
  nwindow('/comm/post.php?form=write&zip1=e_zip1&zip2=e_zip2&address=e_addr1', 'ezipcode', '510' , '400' ,'yes','yes');
  }
}
// ÇÏ³ªÀÏ°æ¿ì
function zipcode(url){
 if(url) {
  nwindow(""+url+"/common/post.php?form=write&zip1=zip1&zip2=zip2&address=addr1", 'zipcode', '510' , '400' ,'yes','yes');
  } else {
  nwindow('/comm/post.php?form=write&zip1=zip1&zip2=zip2&address=addr1', 'zipcode', '510' , '400' ,'yes','yes');
  }
}
// Á¤ÇÒ¶§
function zipcode_edit(form, zip1, zip2, address, url){
 if(url) {
  nwindow(""+url+"/common/post.php?form="+form+"&zip1="+zip1+"&zip2="+zip2+"&address="+address+"", 'zipcode', '510' , '400' ,'yes','yes');
  } else {
  nwindow('/comm/post.php?form='+form+'&zip1='+zip1+'&zip2='+zip2+'&address='+address+'', 'zipcode', '510' , '400' ,'yes','yes');
  }
}
//  ÇÁ¸°Æ® °ü·Ã ÇÔ¼ö
function printDiv () {
if (document.all && window.print) {
window.onbeforeprint = beforeDivs;
window.onafterprint = afterDivs;
window.print();
}
}
function beforeDivs () {
if (document.all) {
objContents.style.display = 'none';
objSelection.innerHTML = document.all['d1'].innerHTML;
}
}
function afterDivs () {
if (document.all) {
objContents.style.display = 'block';
objSelection.innerHTML = "";
}
}
function get_result(argform,argSel,argRes)
{
   var f=eval('document.'+ argform);
   formSel=eval("f."+argSel);
   formRes=eval("f."+argRes);
   res=new Array();
   for(var i=0;i<formSel.length;i++)
   {
   res[i]=formSel.options[i].value;
   }
   res=res.join("|");
   formRes.value=res;
}

function up(argform,argSel,argRes)
{
   var f=eval('document.'+ argform);
   formSel  = eval("f."+argSel);
   if(!formSel.value) { return;}
   thisIndex  = formSel.selectedIndex;
   if(!thisIndex){return;}
   formSel.value=null;
   prevIndex=thisIndex-1;
   tempText=formSel.options[prevIndex].text;
   tempValue=formSel.options[prevIndex].value;
   formSel.options[prevIndex]        = new Option(formSel.options[thisIndex].text,formSel.options[thisIndex].value);
   formSel.options[thisIndex]        = new Option(tempText,tempValue);
   formSel.value=formSel.options[prevIndex].value;
   get_result(argform,argSel,argRes);
}
function down(argform,argSel,argRes)
{
var f=eval('document.'+ argform);
   formSel = eval("f."+argSel);
   if(!formSel.value){ return;}
   thisIndex = formSel.selectedIndex;
   if(thisIndex+1>=formSel.length) { return;}
   formSel.value=null;
   prevIndex=thisIndex+1;
   tempText=formSel.options[prevIndex].text;
   tempValue=formSel.options[prevIndex].value;
   formSel.options[prevIndex]        = new Option(formSel.options[thisIndex].text,formSel.options[thisIndex].value);
   formSel.options[thisIndex]        = new Option(tempText,tempValue);
   formSel.value=formSel.options[prevIndex].value;
   get_result(argform,argSel,argRes);
}
function move(index,to,list)
{
  var f = document.write;
  var total = list.options.length-1;
  var chk = 0;

  for (var i = 0; i < list.length; i++)
  {
    if (list.options[i].selected == true)
    {
      chk = 1;
      break;
    }
  }
  if (!chk)
  {
    alert('ÀÌµ¿ÇÒ Ç×¸ñÀ» ¼±ÅÃÇØ ÁÖ½Ê±â ¹Ù¶ø´Ï´Ù.');
    return false;
  }

  if (index == -1) return false;
  if (to == +1 && index == total) return false;
  if (to == -1 && index == 0) return false;

  var items = new Array;
  var values = new Array;

  for (i = total; i >= 0; i--)
  {
    items[i] = list.options[i].text;
    values[i] = list.options[i].value;
  }

  for (i = total; i >= 0; i--)
  {
    if (index == i)
    {
      list.options[i + to] = new Option(items[i],values[i], 0, 1);
      list.options[i] = new Option(items[i + to], values[i + to]);
      i--;
    }
    else
    {
      list.options[i] = new Option(items[i], values[i]);
    }
  }
}
function del_menu(list)
{
  var f = document.write;
  var chk  = 0;

  for (var i = 0; i < list.length; i++)
  {
    if (list.options[i].selected == true)
    {
      list.options[i] = null;
      chk++;
      break;
    }
  }

  if (!chk)
  {
    alert('Á¦¿Ü½ÃÅ³ Ç×¸ñÀ» ¼±ÅÃÇØ ÁÖ½Ê½Ã¿ä         ');
    return false;
  }
}
// ±¸/±º ÀÚ¹Ù½ºÅ©¸³Æ®
var countys   = new Array();
countys[0]    = new Array('ÀüÃ¼');
countys[1]    = new Array('ÀüÃ¼','°­³²±¸','°­µ¿±¸','°­ºÏ±¸','°­¼­±¸','°ü¾Ç±¸','±¤Áø±¸','±¸·Î±¸','±ÝÃµ±¸','³ë¿ø±¸','µµºÀ±¸','µ¿´ë¹®±¸','µ¿ÀÛ±¸','¸¶Æ÷±¸','¼­´ë¹®±¸','¼­ÃÊ±¸','¼ºµ¿±¸','¼ººÏ±¸','¼ÛÆÄ±¸','¾çÃµ±¸','¿µµîÆ÷±¸','¿ë»ê±¸','ÀºÆò±¸','Á¾·Î±¸','Áß±¸','Áß¶û±¸');
countys[2]    = new Array('ÀüÃ¼','°­¼­±¸','±ÝÁ¤±¸','³²±¸','µ¿±¸','µ¿·¡±¸','ºÎ»êÁø±¸','ºÏ±¸','»ç»ó±¸','»çÇÏ±¸','¼­±¸','¼ö¿µ±¸','¿¬Á¦±¸','¿µµµ±¸','Áß±¸','ÇØ¿î´ë±¸','±âÀå±º');
countys[3]    = new Array('ÀüÃ¼','³²±¸','´Þ¼­±¸','µ¿±¸','ºÏ±¸','¼­±¸','¼ö¼º±¸','Áß±¸','´Þ¼º±º');
countys[4]    = new Array('ÀüÃ¼','°è¾ç±¸','³²±¸','³²µ¿±¸','µ¿±¸','ºÎÆò±¸','¼­±¸','¿¬¼ö±¸','Áß±¸','°­È­±º','¿ËÁø±º');
countys[5]    = new Array('ÀüÃ¼','±¤»ê±¸','³²±¸','µ¿±¸','ºÏ±¸','¼­±¸');
countys[6]    = new Array('ÀüÃ¼','´ë´ö±¸','µ¿±¸','¼­±¸','À¯¼º±¸','Áß±¸');
countys[7]    = new Array('ÀüÃ¼','³²±¸','µ¿±¸','ºÏ±¸','Áß±¸','¿ïÁÖ±º');
countys[8]    = new Array('ÀüÃ¼','°­¸ª½Ã','µ¿ÇØ½Ã','»ïÃ´½Ã','¼ÓÃÊ½Ã','¿øÁÖ½Ã','ÃáÃµ½Ã','ÅÂ¹é½Ã','°í¼º±º','¾ç±¸±º','¾ç¾ç±º','¿µ¿ù±º','ÀÎÁ¦±º','Á¤¼±±º','Ã¶¿ø±º','ÆòÃ¢±º','È«Ãµ±º','È­Ãµ±º','È²¼º±º');
countys[9]    = new Array('ÀüÃ¼','°í¾ç½Ã ´ö¾ç±¸','°í¾ç½Ã ÀÏ»êµ¿±¸','°í¾ç½Ã','ÀÏ»ê¼­±¸','°úÃµ½Ã','±¤¸í½Ã','±¤ÁÖ½Ã','±¸¸®½Ã','±ºÆ÷½Ã','±èÆ÷½Ã','³²¾çÁÖ½Ã','µ¿µÎÃµ½Ã','ºÎÃµ½Ã ¼Ò»ç±¸','ºÎÃµ½Ã ¿ÀÁ¤±¸','ºÎÃµ½Ã ¿ø¹Ì±¸','¼º³²½Ã ºÐ´ç±¸','¼º³²½Ã ¼öÁ¤±¸','¼ö¿ø½Ã ±Ç¼±±¸','¼ö¿ø½Ã ¿µÅë±¸','¼ö¿ø½Ã Àå¾È±¸','¼ö¿ø½Ã ÆÈ´Þ±¸ ','½ÃÈï½Ã',
'¾È»ê½Ã ´Ü¿ø±¸','¾È»ê½Ã »ó·Ï±¸','¾È¼º½Ã','¾È¾ç½Ã µ¿¾È±¸','¾È¾ç½Ã ¸¸¾È±¸','¾çÁÖ½Ã','¿À»ê½Ã','¿ëÀÎ½Ã ±âÈï±¸','¿ëÀÎ½Ã ¼öÁö±¸','¿ëÀÎ½Ã Ã³ÀÎ±¸','ÀÇ¿Õ½Ã','ÀÇÁ¤ºÎ½Ã','ÀÌÃµ½Ã','ÆÄÁÖ½Ã','ÆòÅÃ½Ã','Æ÷Ãµ½Ã','ÇÏ³²½Ã','È­¼º½Ã','°¡Æò±º','¾çÆò±º','¿©ÁÖ±º','¿¬Ãµ±º');
countys[10]   = new Array('ÀüÃ¼','°ÅÁ¦½Ã','±èÇØ½Ã','¸¶»ê½Ã','¹Ð¾ç½Ã','»çÃµ½Ã','¾ç»ê½Ã','ÁøÁÖ½Ã','ÁøÇØ½Ã','Ã¢¿ø½Ã','Åë¿µ½Ã','°ÅÃ¢±º','°í¼º±º','³²ÇØ±º','»êÃ»±º','ÀÇ·É±º','Ã¢³ç±º','ÇÏµ¿±º','ÇÔ¾È±º','ÇÔ¾ç±º','ÇÕÃµ±º');
countys[11]   = new Array('ÀüÃ¼','°æ»ê½Ã','°æÁÖ½Ã','±¸¹Ì½Ã','±èÃµ½Ã','¹®°Ï½Ã','»óÁÖ½Ã','¾Èµ¿½Ã','¿µÁÖ½Ã','¿µÃµ½Ã','Æ÷Ç×½Ã ³²±¸','Æ÷Ç×½Ã ºÏ±¸','°í·É±º','±ºÀ§±º','ºÀÈ­±º','¼ºÁÖ±º','¿µ´ö±º','¿µ¾ç±º','¿¹Ãµ±º','¿ï¸ª±º','¿ïÁø±º','ÀÇ¼º±º','Ã»µµ±º','Ã»¼Û±º','Ä¥°î±º');
countys[12]   = new Array('ÀüÃ¼','±¤¾ç½Ã','³ªÁÖ½Ã','¸ñÆ÷½Ã','¼øÃµ½Ã','¿©¼ö½Ã','¿©Ãµ½Ã','°­Áø±º','°íÈï±º','°î¼º±º','±¸·Ê±º','´ã¾ç±º','¹«¾È±º','º¸¼º±º','½Å¾È±º','¿µ±¤±º','¿µ¾Ï±º','¿Ïµµ±º','Àå¼º±º','ÀåÈï±º','Áøµµ±º','ÇÔÆò±º','ÇØ³²±º','È­¼ø±º');
countys[13]   = new Array('ÀüÃ¼','±º»ê½Ã','±èÁ¦½Ã','³²¿ø½Ã','ÀÍ»ê½Ã','ÀüÁÖ½Ã ´öÁø±¸','ÀüÁÖ½Ã ¿Ï»ê±¸','Á¤À¾½Ã','°íÃ¢±º','¹«ÁÖ±º','ºÎ¾È±º','¼øÃ¢±º','¿ÏÁÖ±º','ÀÓ½Ç±º','Àå¼ö±º','Áø¾È±º');
countys[14]   = new Array('ÀüÃ¼','¼­±ÍÆ÷½Ã','Á¦ÁÖ½Ã');
countys[15]   = new Array('ÀüÃ¼','°è·æ½Ã','°øÁÖ½Ã','³í»ê½Ã','º¸·É½Ã','¼­»ê½Ã','¾Æ»ê½Ã','Ãµ¾È½Ã','±Ý»ê±º','´çÁø±º','ºÎ¿©±º','¼­Ãµ±º','¿¬±â±º','¿¹»ê±º','Ã»¾ç±º','ÅÂ¾È±º','È«¼º±º');
countys[16]   = new Array('ÀüÃ¼','Á¦Ãµ½Ã','Ã»ÁÖ½Ã »ó´ç±¸','Ã»ÁÖ½Ã Èï´ö±¸','ÃæÁÖ½Ã','±«»ê±º','´Ü¾ç±º','º¸Àº±º','¿µµ¿±º','¿ÁÃµ±º','À½¼º±º','ÁõÆò±º','ÁøÃµ±º','Ã»¿ø±º');
function cityChange(add,selected) {
  var city=document.write.city;
  var county=document.write.county;
  var k = false;
  if(add) city.selectedIndex  = add;
/* ¿É¼Ç¸Þ´º»èÁ¦ */
  for (i=county.length-1; i>=0; i--){
    county.options[i] = null;
  }
/* ¿É¼Ç¹Ú½ºÃß°¡ */
  for (i=0; i < countys[add].length;i++){
    if(selected == countys[add][i]) k  = true; else k=false;
   // county.options[i] = new Option(countys[add][i], countys[add][i],k,k);
    county.options[i] = new Option();
    county.options[i].text = countys[add][i];   
    county.options[i].value = countys[add][i];
    county.options[i].selected = k;
    county.options[i].defaultSelected = k;
  }
}
// sms°ü·Ã ±ÛÀÚ¼ö Á¦ÇÑ
function textarea_cut(form,length_limit)
{   
  
   var length = calculate_msglen(form.value);  
   var tlimit = document.getElementById("textlimit");
   var msgv = document.write.tran_msg;
   tlimit.innerText = length;
   if (length > length_limit) {
       alert("ÃÖ´ë " + length_limit + "byteÀÌ¹Ç·Î ÃÊ°úµÈ ±ÛÀÚ¼ö´Â ÀÚµ¿À¸·Î »èÁ¦µË´Ï´Ù.");
       msgv.value =  msgv.value.replace(/\r\n$/, "");
       msgv.value = assert_msglen( msgv.value, length_limit);
   }
}

function calculate_msglen(message)
{
   var nbytes = 0;

   for (i=0; i<message.length; i++) {
       var ch = message.charAt(i);
       if(escape(ch).length > 4) {
           nbytes += 2;
       } else if (ch == '\n') {
           if (message.charAt(i-1) != '\r') {
               nbytes += 1;
           }
       } else if (ch == '<' || ch == '>') {
           nbytes += 4;
       } else {
           nbytes += 1;
       }
   }

   return nbytes;
}

function assert_msglen(message, maximum)
{
   var inc = 0;
   var nbytes = 0;
   var msg = "";
   var msglen = message.length;

   for (i=0; i<msglen; i++) {
       var ch = message.charAt(i);
       if (escape(ch).length > 4) {
           inc = 2;
       } else if (ch == '\n') {
           if (message.charAt(i-1) != '\r') {
               inc = 1;
           }
       } else if (ch == '<' || ch == '>') {
           inc = 4;
       } else {
           inc = 1;
       }
       if ((nbytes + inc) > maximum) {
           break;
       }
       nbytes += inc;
       msg += ch;
   }
   textlimit.innerText = nbytes;
   return msg;
}


function mSelect(input_name,input_value) {
      if(!(fn = document.getElementById(input_name))) {
        name = document.getElementsByName(input_name);
        fn = name[0];
      }
      if(fn!=null && input_value != '') {
        if(fn.type=='radio') {
          count = 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.options[0].selected = true;
              }
              break;
        case 'text' :
        case 'textarea' :
          fn.value = input_value;
          break;
            default :
          }
    }
  } 
}
