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}글자 이상이어야 합니다.",
    maxbyte    : "입력된 내용의 길이가 {maxbyte}글자를 초과할 수 없습니다.",
    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 = /^[가-힣]+$/;
    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(){
    var code = event.keyCode;
    //백스페이스(8), -(189), 숫자만 입력되게 한다.
    if( code !=8 && (code < 48 || code > 57) && code != 189) {
        event.returnValue = false;
    }else {
        return true;
    }    
}
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;
  }
}

function onlyNumbers(){
    var code = event.keyCode;
    //백스페이스(8), -(189), 숫자만 입력되게 한다.
    if( code !=8 && (code < 48 || code > 57) && code != 189) {
        event.returnValue = false;
    }else {
        return true;
    }    
}



/**
 *  한글만 과 숫자 입력받는다.
 *
 *  사용법 : onKeyDown='onlyHangleOfNumber()'
 */
function onlyHangleOfNumber()
{
    var ek = event.keyCode
    if( ek != 13 && ek != 9 && ek != 8 && ek != 32 && ek != 46 && ek != 45 && ((ek < 48) ||(ek > 57)) )
     event.returnValue=false;
}
/**
 *  한글만 입력받는다.
 *
 *  사용법 : onKeyDown='onlyHangle()'
 */
function onlyHangle()
{
    var ek = event.keyCode;
    if( ek != 13 && ek != 9 && ek != 8 && ek != 32 && ek != 46 && ek != 45 )
     event.returnValue=false;
}
function onleyEngNumber(input){
	var str = input.value;
	for(var i=0;i<str.length;i++)
	{
 
		if(!((str.charCodeAt(i) >= 48 && str.charCodeAt(i) <= 57) || (str.charCodeAt(i) >= 65 && str.charCodeAt(i) <= 90) ||(str.charCodeAt(i) >= 97 && str.charCodeAt(i) <= 122)))
		{
			alert('영문과 숫자만 입력이 가능합니다.');
			input.value = '';
		}
	}
}
function onleyEngNumberGolJum(input){
	var str = input.value;
	for(var i=0;i<str.length;i++)
	{
 
		if(!((str.charCodeAt(i) >= 48 && str.charCodeAt(i) <= 57) || (str.charCodeAt(i) >= 65 && str.charCodeAt(i) <= 90) ||(str.charCodeAt(i) >= 97 && str.charCodeAt(i) <= 122)))
		{
			var flag = true;
			if (str.charCodeAt(i) == 46 || str.charCodeAt(i)  == 64)
			{
				flag = false;
			}
			if (flag)
			{
				alert('영문과 숫자만 입력이 가능합니다.');
				input.value = '';
			}
		}
	}
}
/**
 *  숫자에서 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 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('/common/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('/common/common/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('/common/post.php?form=write&zip1=zip1&zip2=zip2&address=addr1', '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 SFun_NextFocus(frm,cls,len) {
 if(cls.value.length == len) {
  for(i=0;i<frm.length;i++) {
   if(cls.name == frm.elements[i].name) {
    index = i + 1;
   }
  }
  frm.elements[index].focus();
  return;
 }
};


