try { 
	if (typeof(Prototype) == "undefined")
		alert("[ERROR] Prototype library required.");
} catch(e) {
	alert(e.description);
}


String.prototype.trim = function () {
	return this.replace(/^\s+|\s+$/g, "");
}


/**
 * NCScriptUtil
 * @author Yu Chi-su
 */
var NCScriptUtilClass = Class.create();
NCScriptUtilClass.prototype = {
	initialize : function() {
		this.Cookie = new CookieUtilClass();
		this.Event = new EventUtilClass();
	},
	getQueryString : function() {
		var pos = document.URL.indexOf('?');
		if (pos == -1) return "";
		return document.URL.substr(pos+1);
	},
	getQueryParams : function() {
		return this.getQueryString().toQueryParams();
	},
	getPath : function() {
		var path = document.location.pathname;
		path = path.substr(0, path.lastIndexOf("/")) + "/";
		return path;
	},
	JSONToQueryString : function(queryObject) {
		return $H(queryObject).toQueryString();
	}
}

/**
 * Eventutil
 * @author Yu Chi-su
 */
var EventUtilClass = Class.create();
EventUtilClass.prototype = {
	initialize : function() {
	},
	addEvent : function(targetObject, eventName, eventHandler) {
		Event.observe(targetObject, eventName, eventHandler);
	},
	removeEvent : function(targetObject, eventName, eventHandler) {
		Event.stopObserve(targetObject, eventName, eventHandler);
	}
}

/**
 * Cookie util
 * @author Yu Chi-su
 */
var CookieUtilClass = Class.create();
CookieUtilClass.prototype = {
	initialize : function() {
	},
	getCookie : function (name) {
		var first;
		var str = name + "=";
		if (document.cookie.length > 0) {
			find = document.cookie.indexOf(str);
			if (find == -1) return null;
			first = find + str.length;
			end = document.cookie.indexOf(";", first);
			if (end == -1) end = document.cookie.length;
			return unescape(document.cookie.substring(first, end));
		}
	},
	setCookie : function(name, value, expireDate) {
		var cookieStr = name + "=" + escape(value) + ((expireDate == null) ? "" : (";expires=" + expireDate.toGMTString()));
		document.cookie = cookieStr;
	},
	removeCookie : function(name) {
		var exp = new Date();
		exp.setTime(exp.getTime()-1);
		document.cookie = name + "=" + ";expires=" + exp.toGMTString() + "; path=/";
	}
}
var NCScriptUtil = new NCScriptUtilClass();

/**
 * support aspect js
 * @author Yu Chi-su
 */
Aspect = {
	addBeforeAdvice : function(obj, fname, beforeAdvice) {
		var oldFunc = obj[fname];
		obj[fname] = function() {
			beforeAdvice(arguments, obj);
			return oldFunc.apply(this,arguments);
		};
	},
	addAfterAdvice : function(obj, fname, afterAdvice) {
		var oldFunc = obj[fname];
		obj[fname] = function() {
			result = oldFunc.apply(this, arguments);
			try{
				return result;
			} finally {
				afterAdvice(result, arguments, obj);
			}
		};
	},
	addAroundAdvice : function(obj, fname, around) {
		var oldFunc = obj[fname];
		obj[fname] = function(args) {
			return around(arguments, obj, 
					function(){
						return oldFunc.apply(this, obj[fname].arguments);
					} 
			);
		};
	}
};

/**
 * String builder
 * @author Yu Chi-su
 */
var StringBuilder = Class.create();
StringBuilder.prototype = {
	initialize : function() {
		this._initialText = arguments[0];
		this._parts = [];
		
		if ((typeof(this._initialText) == 'string') && (this._initialText.length != 0)) {
		    _parts.push(this._initialText);
		}		
	},
	append : function(text) {
        if ((text == null) || (typeof(text) == 'undefined')) {
            return;
        }
        if ((typeof(text) == 'string') && (text.length==0)) {
            return;
        }
        this._parts.push(text);
    },
    appendLine : function(text) {
        this.append(text);
        this._parts.push('\r\n');
    },
    clear : function() {
        this._parts.clear();
    },
    isEmpty : function() {
        return (this._parts.length == 0);
    },
    toString : function(delimiter) {
        return this._parts.join(delimiter||'');
    }
}

String.format = function(format) {
    var result = new StringBuilder();
    for (var i=0; ; ) {
        var next = format.indexOf("{",i);
        if (next < 0) {
            result.append(format.slice(i));
            break;
        }
        result.append(format.slice(i,next));
        i = next + 1;
        
        if (format.charAt(i)=='{') {
            result.append('{');
            i++;
            continue;
        }
        var next = format.indexOf("}",i);
        var brace = format.slice(i,next).split(':');
        var argNumber = Number.parse(brace[0])+1;
        var arg = arguments[argNumber];
        if (arg == null) {
            arg = '';
        }
        if (arg.toFormattedString)
            result.append(arg.toFormattedString(brace[1]?brace[1]:''));
        else
            result.append(arg.toString());i=next+1;
    }
    return result.toString();
}

Number.parse = function(value) {
    if (!value||(value.length==0)) {
        return 0;
    }
    return parseFloat(value);
}

/**
 * Validation Manager
 * @author Yu Chi-su
 */
var ValidationManager = Class.create();
ValidationManager.prototype = {
	initialize : function() {
		this.validators = new Array();
	},
	add : function(validator) {
		this.validators.push(validator);
	},
	isValid : function() {
		for (var i = 0; i < this.validators.length; i++) {
			if (!this.validators[i].doValidate())
				return false;
		}
		return true;
	}
}

/**
 * Value validator
 * @author Yu Chi-su
 */
var ValueValidator = Class.create();
ValueValidator.prototype = {
	/*
		@controlName : html form control name
		@conditions :
			minLength : minium value length
			maxLength : maximum value length
			errorMessage : error message prefix
			doFocus : focus on control
	*/
	initialize : function(controlName, conditions) {
		this.controlName = controlName; 
		this.conditions = conditions;
		try {
			if (typeof(conditions.maxLength) != "undefined")
				$(this.controlName).maxLength = conditions.maxLength;
		} catch(e) { }
	},
	doValidate : function() {
		try {
			var c = this.conditions;
			var control = $(this.controlName);
			
			if (control == null) {
				alert(String.format("[ERROR VALUE VALIDATOR] invalid control name '{0}'", this.controlName));
				return false;
			}
			if (typeof control.value == "undefined") {
				alert(Strinf.format("[ERROR VALUE VALIDATOR] control '{0}' have not value property.", this.controlName));
				return false;		
			}
			if (typeof c.minLength != "undefined" && control.value.strip().length < c.minLength) {
				if (c.errorMessage != null) {
					if (control.value.strip().length > 0) {
						alert(String.format("{0} {1}자 이상 입력해 주세요.", c.errorMessage, c.minLength));
					} else {
						if (control.tagName == "INPUT" || control.tagName == "TEXTAREA") {
							alert(String.format("{0} 입력해 주세요.", c.errorMessage));
						} else if (control.tagName == "SELECT") {
							alert(String.format("{0} 선택해 주세요.", c.errorMessage));
						}				
					}
				}
				if (c.doFocus != false) {
					control.focus();
				}
				return false;
			}
			if (typeof c.maxLength != "undefined" && control.value.strip().length > c.maxLength) {
				if (c.errorMessage != null)
					alert(String.format("{0} {1}자 이하로 입력해 주세요.", c.errorMessage, c.maxLength));
				if (c.doFocus != false) control.focus();
				return false;
			}
			return true;
		} catch(e) {
			alert(e.description);
			return false;
		}
	}
}

/**
 * custom function support validator
 * @author Yu Chi-su
 */
var CustomValidator = Class.create();
CustomValidator.prototype = {
	initialize : function(func) {
		if (typeof func == "undefined")
			alert("function is not defined."); 
		this.validationFunction = func;
	}
	,doValidate : function() {
		if (null != this.validationFunction)
			return this.validationFunction();
		else
			return false;
	}
}

/**
 * prototype js extension
 * @author Yu Chi-su
 */
Object.extend(Element.Methods, {
	/*
	 * set text autocompletion of inputbox.
	 * usage : Element.setAutoComplete(element, false);
	 *         $("elementName").setAutoComplete(false);
	 */
	setAutoComplete : function(element, autoComplete) {
		try {
			element.autocomplete = (autoComplete) ? "on" : "off";
		} catch(e) { }
	}
});
