﻿

Object.prototype.extend = function(object, override, overNull){
    var extend = function(dest, source, _override, _overNull){
        for (prop in source) 
            if (((_override || typeof dest[prop] == "undefined") || (_overNull && dest[prop] == null)) && (!Object.isOriginal || !Object.isOriginal(prop))) 
                dest[prop] = source[prop];
        return dest;
    }
	if(object && typeof(object) == "object")
    	return extend.apply(this, [this, object, override != false,overNull]);
	return this;
};

String.prototype.extend({
    
    endsWith: function( s){
        return (this.substr(this.length - s.length) == s);
    },
    
    startsWith: function( s){
        return (this.substr(0, s.length) == s);
    },
    
    trimLeft: function(){
        return this.replace(/^\s*/, "");
    },
	
    trimRight: function(){
        return this.replace(/\s*$/, "");
    },
	
    trim: function(){
        return this.trimRight().trimLeft();
    }, 
	
    toLower: function(){
        return this.toLowerCase();
    }, 
		
    toUpper: function(){
        return this.toUpperCase();
    },
	
	toFirstUpper : function(){
		var s = "";
		for(var i=0; i<this.length; i++) {
			if(i==0) s += this[i].toUpperCase();
			else s += this[i].toLowerCase();
		}
		return s;
	},
		
    replaceAll: function(search, replace){         var regex = new RegExp(search, ["g"]);
        return this.replace(regex, replace);
    },
	
	repeat : function( times) {
		if(times > 0) 
			return new Array(times + 1).join(this);
		return "";
	},
    
    format: function(){
        var s = this;
        for (var i = 0; i != arguments.length; i++) 
            s = s.replaceAll("\\{" + i + "\\}", arguments[i]);
        return s;
    },
	
    isEmpty: function(){
        return this.trim() == "";
    },
    
    right: function( count, fill){
        if (count == this.length) 
            return this;
        if (count > this.length) {
            if (fill == null || fill == undefined || fill.isEmpty()) 
                return this;
            var s = this;
            while (s.length < count) 
                s = fill.right(count - s.length) + s;
            return s;
        }
        if (count < this.length) 
            return this.substr(this.length - count, count);
    },
	
    left: function(count, fill, reallength){
        if (this.bytesCount() <= count) 
            return this;
        var s = "";
        var fillLength = (fill ? fill.bytesCount() : 0);
        for (var i = 0; i < this.length; i++) {
            if ((s.bytesCount() + fillLength + String(this.charAt(i)).bytesCount()) <= count) 
                s += String(this.charAt(i));
            else 
                break;
        }
        return s + fill;
    },
    
    bytesCount: function(){
        return this.replace(/[^\x00-\xff]/g, "aa").length;
    },
    
    toJSONString: function(){
        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        };
        if (/["\\\x00-\x1f]/.test(this)) {
            return '"' +
            this.replace(/([\x00-\x1f\\"])/g, function(a, b){
                var c = m[b];
                if (c) 
                    return c;
                c = b.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) +
            '"';
        }
        return '"' + this + '"';
    },
    
    parseJSON: function(){
        try {
            return eval('(' + this + ')');
        } 
        catch (e) {
            return null;
        }
    },
	parseRegexp : function() {		
		try{
			var i = this.lastIndexOf("/");
			if(this.startsWith("/") && i>0)
				return new RegExp(this.slice(1,i),this.slice(i+1,this.length));
			return new RegExp(this);
		}catch(e){}
		return null;
	}
}, false);


Object.prototype.extend({
    
	toJSONString : function() {
	    var a = [];  
	    for(var k in this) {
	        if(!Object.isOriginal(k)) continue;
	        var v = this[k];
	        switch(typeof(v)) {
	            case 'object':
	                if (v) if (typeof v.toJSONString === 'function') a.push(k.toJSONString() + ':' + v.toJSONString());
                    else a.push(k.toJSONString() + ':null');                    
	                break;
	            case 'string':
                case 'number':
                case 'boolean':
                    a.push(k.toJSONString() + ':' + v.toJSONString());
                    break;
	        }
	    }
	    return '{' + a.join(',') + '}'; 
	},
	
	isIn : function( array) {
		if(array instanceof Array) 
			return array.indexOf(this) >= 0;
		return false;
	}	
});


Function.prototype.extend({
        
    delegate : function( context) {
        var _this = this;
        return function() { _this.apply(context,arguments);};
    },    
	
    callback : function( method, beginMethod, context) {    
        var _this = this;   
		var o = context || this;
        return function() {
            if(beginMethod) beginMethod.apply(o,arguments);
            _this.apply(o,arguments);
            if(method) method.apply(o,arguments);
        };
    }
});



if(!Array.prototype.push) {
	function array_push() {
		for(var i=0;i<arguments.length;i++)
			this[this.length]=arguments[i];
		return this.length;
	}
	Array.prototype.push = array_push;
}
if(!Array.prototype.pop) {
	function array_pop(){
		lastElement = this[this.length-1];
		this.length = Math.max(this.length-1,0);
		return lastElement;
	}
	Array.prototype.pop = array_pop;
}

Array.prototype.extend({
    
    toJSONString : function() {
        var a = [];
        for(var i=0; i<this.length; i++) {
            var v = this[i];
            switch(typeof(v)) {
                case "object":
                    if(v) if (typeof v.toJSONString === 'function') a.push(v.toJSONString());                    
                    else a.push("null");
                    break;
                case 'string':
                case 'number':
                case 'boolean':
                    a.push(v.toJSONString());
                    break;
            }
        }
        return '[' + a.join(',') + ']';
    },
    
    contains : function( value, ignoreCase) {
        for(var i=0; i<this.length; i++) {
            if (this[i] == value) return true;
			if(ignoreCase == true && typeof(this[i]) == "string" && typeof(value) == "string" && String(this[i]).toLowerCase() == String(value).toLowerCase()) return true;
        }
        return false;
    },
    
    indexOf : function( o, p, value) {
        for(var i=0; i<this.length; i++) {
			if (typeof(this[i]) == "object" && p) {
				if(!this[i][p]) continue;
				if(value && this[i][p] != value) continue;
				return i;
			}
			else {
				if (this[i] == o) 
					return i;
			}
        }
        return -1;
    },   
	
    remove : function() {
		for (var i = 0; i < arguments.length; i++) {
			var index = this.indexOf(arguments[i]);
			if (index == -1) 
				continue;
			this.splice(index, 1);
		}
    },
	
	removeEmpty : function() {
		for(var i=this.length -1; i>=0; i--) {
			if(Object.isNull(this[i]) || this[i] == "")
				this.splice(i,1);
		}
		return this;
	},
	
	each : function( iterator, context) {
		var method = context ? iterator.createDelegate(context) : iterator;
		for(var i=0,length = this.length; i < length; i++){
			if(method(this[i],i) == false) break;
		}
	},
	
	last : function() {
		if(this.length <= 0) return null;
		return this[this.length -1];
	},
	
	first : function() {
		if(this.length <= 0) return null;
		return this[0];
	}
});


Array.parse = function( object) {
	var array = [];
    if(object.length != undefined && object.length != null && typeof(object) != "string" && typeof(object.length) == "number") {
		if(object.length == 0) return array;
        for(var i=0; i<object.length; i++) 
           array.push(object[i]); 
    }
    else if(!(object instanceof Function) && typeof(object) == "object"){
		var regexp = null;
		var includeFunction = false;
		if(arguments[1]) { 
			if(arguments[1] instanceof RegExp) 
				regexp = arguments[1];
			else 
				regexp = new RegExp(pattern,"g");
		}	
		if(arguments[2] && arguments[2] == true)
			includeFunction = true;		
        for(var p in object) {				
            if(object[p]) {
				if((!includeFunction && object[p] instanceof Function) || (!object[p] || regexp.test(p))) continue;
				array.push(object[p]);
				array[p] = array.last();
			}
        }
    }
	else if(typeof(object) == "string" && arguments[1] && typeof(arguments[1]) == "string") {
		var a = object.split(arguments[1]);
		var removeBlanks = true;
		if(arguments[2] && arguments[2] == false)
			removeBlanks = false;
		for(var i=0; i<a.length; i++){
			if(!a[i] && removeBlanks) continue;
			array.push(a[i]);
		}		
	}
	else {
		array.push(object);
	}
	return array;
};

Boolean.prototype.extend({
    
    toJSONString : function() {
        return String(this);
    }
});


Date.prototype.extend({
    
    toJSONString : function() {
        return '"' + this.format() + '"';
    },
    
	
    format : function( dateTimeFormat) {
        var formatString = dateTimeFormat || "yyyy-MM-dd hh:mm:ss";
        var matchYear = formatString.match(/(y+)/);
        var matchMonth  = formatString.match(/(M+)/);
        var matchDate = formatString.match(/(d+)/);
        var matchHour = formatString.match(/(h+)/);
        var matchMinute = formatString.match(/(m+)/);
        var matchSecond = formatString.match(/(s+)/);
        if(matchYear)
            formatString = formatString.replace(matchYear[0],String(this.getFullYear()).right(matchYear[1].length,"0"));
        if(matchMonth)
            formatString = formatString.replace(matchMonth[0],String(this.getMonth() + 1).right(matchMonth[1].length,"0"));
        if(matchDate)
            formatString = formatString.replace(matchDate[0],String(this.getDate()).right(matchDate[1].length,"0"));
        if(matchHour)
            formatString = formatString.replace(matchHour[0],String(this.getHours()).right(matchHour[1].length,"0"));
        if(matchMinute)
            formatString = formatString.replace(matchMinute[0],String(this.getMinutes()).right(matchMinute[1].length,"0"));
        if(matchSecond)
            formatString = formatString.replace(matchSecond[0],String(this.getSeconds()).right(matchSecond[1].length,"0"));
        return formatString;
    },
	
    addDays : function( days) {
        this.setDate(this.getDate() + days);
        return this;
    },
	
    addTimes : function( times) {
        var time = this.getTime() + times;
        this.setTime(time);
        return this;
    }
});


Number.prototype.extend({
	
    toJSONString : function() {
        return isFinite(this) ? String(this) : 'null';
    },
	
    toFixed : function( length) {
        if( isNaN(length) || length == null) length   =   0;
        else if(length < 0) length = 0; 
        return  Math.round(this * Math.pow(10 ,length)) / Math.pow(10, length);   
    }	
});

Object.extend({
	$ORIGINAL_REGEXP : null,
	
	create : function( name, object, parent, override) {
		var ns,s = name.split(".");        
	    if(parent && typeof(parent) == "object") ns = parent;
	    else ns = window;
		for(var i=0; i<s.length; i++) {
		    if(typeof ns[s[i]] == "undefined") 
		        ns[s[i]] = (i == s.length -1) ? (object || {}) : {};
			ns = ns[s[i]];	
		}
		return ns;
	},
	
	isOriginal : function( name) {
		if (!this.$ORIGINAL_REGEXP) {
			var o = {};
			var a = [];
			for (var p in o) 
				a.push("(^"+p+"$)");
			this.$ORIGINAL_REGEXP = new RegExp(a.join("|"));			
		}
		return this.$ORIGINAL_REGEXP.test(name);
	},
	
	isNull : function( o) {
		if(o == undefined || o == null)
			return true;
		return false;
	},
	 
	getAttribute : function( object, name) {
		var value = object[name];
		if(Object.isNull(value) && object.getAttribute)
			return object.getAttribute(name);
		return value;
	},
	
	setAttribute : function(object,name,value) {
		if(object.setAttribute) 
			object.setAttribute(name,value);
		object[name] = value;
	}
});


window.Class = {
    $LOADING_CLASSES: {},
    $CLASSES_CALLBACK : {},
    
    register: function(name, method, base, override) {
        if (method && !(method instanceof Function)) return Object.create(name, method, base, override);
        var nameNodes = String(name).split(".");
        className = nameNodes.pop();
        var namespace = nameNodes.length > 0 ? Object.create(nameNodes.join(".")) : window, c;
        if (!namespace[className] || override != false)
            c = method || function() { };
        if (base instanceof Function)
            c = Class.extend(c, base);
        c.prototype.$CLASSNAME = name;
        c.$ISCLASS = true;
        namespace[className] = c;
        return c;
    },
    
    extend: function(method, base) {
        method.prototype = new base();
        method.prototype.constructor = method;
        method.base = base.prototype;
        return method;
    },
    
    load: function(className, callback, url) {
        var _cn = className.replace(/[.]/g, "_");        
        if (this.exists(className)) {
			if(callback) callback();
			return true;
		}
		if (this.$LOADING_CLASSES[_cn] == true) return false;
        if (!url) url = Hrcbc.path() + "/" + className.replace(/[.]/g, "/") + ".js";
        if(callback) this.$CLASSES_CALLBACK[_cn] = callback;
        if (this.exists("Hrcbc.AjaxRequest")) {			
            Hrcbc.AjaxRequest.getText(url, callback ? true : false,function(xmlHttp) {
				var script = xmlHttp.responseText;
				try {	                
	                if (window.execScript) window.execScript(script);
	                else eval.call(window, script);
					Class.loaded(_cn);
	            }
	            catch (e) {
	                	            };	
			});
			Class.$LOADING_CLASSES[_cn] = true;           
        }
        else {
            this.$LOADING_CLASSES[_cn] = true;            
            var htmlHeader = document.getElementsByTagName("head");
            if (htmlHeader.length > 0) {
                var script = document.createElement("script");
                script.src = url;
                script.type = "text/javascript";
                htmlHeader[0].appendChild(script);  
				if (callback) {
					if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
						script.onreadystatechange = function(){
							if (/loaded|complete/.test(this.readyState)) Class.loaded(_cn);
						};
					}
					else script.onload = function() {Class.loaded(_cn);	};
				}				
            }
            else document.write("<script type=\"text/javascript\" {1} src=\"{0}\"></script>".format(url,callback ? ("onload=\"Class.loaded('"+_cn+"');\"") : ""));            
        }
        return this.exists(className);
    },
	
	loaded : function( name) { 
		if(this.$CLASSES_CALLBACK[name]) {
			this.$CLASSES_CALLBACK[name]();
			delete this.$CLASSES_CALLBACK[name];
		}		
	},
    
    exists: function(className) {
        try {
            if (eval("typeof " + className) == "function" || eval("typeof " + className) == "object")
                return true;
        } catch (e) {
        }
        return false;
    }
}


Class.register("Hrcbc", {
    $ISLOAD: false,
    $INITLOAD: false,
    $INITUNOLOAD: false,
    $UNLOAD: true,
    $PATH: null,
    $TRACE: null,
    $SELECTABLE: true,
    $INISELECT: false,
    defaultUploadUrl: "Pages/UploadFile.ashx",
    defaultUploadProgressUrl: "Pages/UploadProgress.ashx",
    blankImageUrl: '/resources/default/images/blank.gif',
    isDebug: true,	
    $MAX_ZORDER : 1 ,
    $STYLES : {},
    
    sendError: function( error) {
		var errorText = (error instanceof Error) ? error.description : String(error);
        if(!errorText) return;
		if(this.isDebug)
			this.trace("Error:" + errorText);
		alert(errorText);        
    },
	
    trace: function( message) {
        if (!this.isDebug) return;
        if (!this.$TRACE) {
            this.$TRACE = document.createElement("div");
            this.$TRACE.style.padding = "10px";
            this.$TRACE.style.lineHeight = "20px";
            this.$TRACE.style.fontSize = "12px";
            this.$TRACE.style.border = "1px solid #999999";
            this.$TRACE.style.overflow = "auto";
            this.$TRACE.style.backgroundColor = "#f5f5f5";
            this.$TRACE.style.color = "#333333";
            this.$TRACE.style.fontFamily = "Arial, Helvetica, sans-serif";
            this.$TRACE.style.height = "200px";
            this.onload(function() {
                document.body.appendChild(Hrcbc.$TRACE);
            });
        }
        this.$TRACE.innerHTML = new Date().toLocaleString() + " ：" + message + "<br />" + this.$TRACE.innerHTML;
        if (Hrcbc.$ISLOAD) {
            document.body.appendChild(Hrcbc.$TRACE);
        }
    },
    ready: function() {
        Hrcbc.$ISLOAD = true;
        if (Hrcbc.load) Hrcbc.load();
    },
    
    onload: function() {
        var args = Array.parse(arguments);
        if (args.length == 0 || !(args[0] instanceof Function)) {
            Hrcbc.sendError("参数错误", Hrcbc.Error.ParameterError);
            return;
        }
        var method = args.shift();
        if (this.$ISLOAD) {
            if (args.length == 0)
                method();
            else
                method.apply(args.shift() || this, args);
        }
        var _method = function() {
            if (args.length == 0)
                method();
            else
                method.apply(args.shift() || this, args);
        };
        if (!this.$INITLOAD) {

            /*@cc_on@*/
            /*@if (@_win32)
            document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
            var ie_onload = document.getElementById("__ie_onload");
            if (ie_onload) {
                ie_onload.onreadystatechange = function() {
                if (this.readyState == "complete") eval("Hrcbc.ready()");
                };
                this.$INITLOAD = true;
            }
            /*@end@*/
            if (document.addEventListener) document.addEventListener("DOMContentLoaded", new Function("Hrcbc.ready()"), false);
            else if (/WebKit/i.test(navigator.userAgent)) {
                var timer = setInterval(function() {
                    if (/loaded|complete/.test(document.readyState)) {
                        Hrcbc.ready();
                        clearInterval(timer);
                    }
                }, 10);
            }
            this.$INITLOAD = true;
        }       
        Hrcbc.Event.addEventListener(Hrcbc, "load", _method);
        if (!this.$INITLOAD) {
            Hrcbc.Event.addEventListener(window, 'load', new Function("Hrcbc.ready()"));
            this.$INITLOAD = true;
        }
    },
	
	getObject : function(name) {		
		if (window.document[name])
            return window.document[name];
        else if (!Hrcbc.Browser.isIE() && document.embeds && document.embeds[name])
            return document.embeds[name];
        else
            return document.getElementById(name);        
	},
    
    onunload: function() {
        var args = Array.parse(arguments);
        if (args.length == 0 || !(args[0] instanceof Function)) {
            Hrcbc.sendError("参数错误", Hrcbc.Error.ParameterError);
            return;
        }
        var method = args.shift();
        var _method = function() {
            if (args.length == 0)
                method();
            else
                method.apply(args.shift() || this, args);
        };
        Hrcbc.Event.addEventListener(Hrcbc, "unload", _method);
        if (!this.$INITUNOLOAD) {
            Hrcbc.Event.addEventListener(window, "unload", Hrcbc.unload);
            this.$INITUNOLOAD = true;
        }
    },
    
    path: function() {
        if (typeof (this.$PATH) == "string") return this.$PATH;
        var script = document.getElementsByTagName("script");
        for (var i = 0; i < script.length; i++) {
            var src = script[i].getAttribute("src");
            if (src.toLowerCase() == "hrcbc.js") {
                this.$PATH = ".";
                break;
            }
            var index = src.toLowerCase().lastIndexOf("/hrcbc.js");
            if (index >= 0) {
                this.$PATH = src.substring(src, index);
                break;
            }
        }
        return this.$PATH;
    },
    
    wait: function(time, method, context, args) {
        var method = method || Hrcbc.wait.caller;
        setTimeout(function() {
            method.apply(context || this, args || method.arguments)
        }, time);
    },
    
    selectable: function(enable) {
        if (this.$INISELECT == false) {
            
            Hrcbc.Event.addEventListener(document, "selectstart", Hrcbc.onselect, false);
            Hrcbc.Event.addEventListener(window, "select", Hrcbc.onselect, false);
        }
        this.$SELECTABLE = enable;
    },
    
    onselect: function() {
        return Hrcbc.$SELECTABLE;
    },
	
    selectNodes : function( htmlElement, searchPath, searchCount) {        
        if(typeof(htmlElement) == "string") 
            htmlElement = document.getElementById(htmlElement);
        if(!htmlElement || searchPath.isEmpty()) return [];
        var elements = [],pathNodes = searchPath.split("/");
        var searchNodes = function( htmlElements, searchOptions, result, isSearchChild) {                                      
            for(var i=0; i < htmlElements.length; i++) {                
                if(!htmlElements[i].hasChildNodes()) continue;                                               
                for(var n=0; n < htmlElements[i].childNodes.length; n++) {
                    var sObject = null,cNode = htmlElements[i].childNodes[n];                   
                    if(cNode.nodeType == "1" && (cNode.nodeName.toLower() == searchOptions.pathNode.toLower() || searchOptions.pathNode == "*")) {
                        var isMatch = true;
                        if(!searchOptions.pathArgs.isEmpty()) {                               isMatch = false;
                            if(searchOptions.pathArgs.charAt(0) == "@") {                                     var attribute = cNode.getAttribute(searchOptions.pathArgs.slice(1,searchOptions.pathArgs.length));
                                if(attribute && !searchOptions.pathArgsValue.isEmpty() && searchOptions.pathArgsValue == attribute) isMatch = true;
                            }
                            else {                                      if(!cNode.hasChildNodes()) continue;                                
                                for(var j=0; j< cNode.childNodes.length; j++) {
                                    if(cNode.childNodes[j].nodeType == "1" && cNode.childNodes[j].nodeName.toLower() == searchOptions.pathArgs.toLower())
                                        if(!searchOptions.pathArgsValue.isEmpty() && cNode.childNodes[j].innerHTML != null && cNode.childNodes[j].innerHTML != "undefined" && cNode.childNodes[j].innerHTML == searchOptions.pathArgsValue)
                                            isMatch = true;                                   
                                }                                
                            }
                        }
                        if(isMatch) sObject = cNode;
                    }
                    if(sObject != null) result.push(sObject);                           else if(isSearchChild == true && cNode.nodeType == 1) result = searchNodes([cNode],searchOptions,result,isSearchChild);                     if(searchCount && searchCount<= result.length) break;
                }
            }
            return result;
        };
        elements.push(htmlElement);
        for(var i=0; i<pathNodes.length; i++) {
            var options = {pathArgs : "",pathArgsValue:""},pathNode = pathNodes[i];
            if(pathNode.isEmpty()) continue; 
            options.pathNode = pathNode;        
            if(pathNode.indexOf("[") >=0 && pathNode.indexOf("]") >=0 ) {
                options.pathArgs = pathNode.slice(pathNode.indexOf("[")+1,pathNode.indexOf("]"));
                options.pathNode = pathNode.slice(0,pathNode.indexOf("["));                       
                if(options.pathArgs.indexOf("=") > 0) {
                    options.pathArgsValue = options.pathArgs.slice(options.pathArgs.indexOf("=")+1,options.pathArgs.length);
                    options.pathArgs = options.pathArgs.slice(0,options.pathArgs.indexOf("="));
                }
            }
            elements =  searchNodes(elements,options,[], (i != 0 && pathNodes[i-1].isEmpty()) || options.pathNode == "*");       
        }
        if(!searchCount)  return elements;
        else return elements.slice(0,searchCount);
    },
	
    selectSingleNode : function( htmlElement, searchPath) {
        var result = this.selectNodes(htmlElement,searchPath,1);
        if(result.length >0) return result[0];
        return null;
    },
    
    getElementSize : function( element) {		
        return  {width : element.offsetWidth || 0, height : element.offsetHeight || 0};
    }, 
	
	isContains : function( container, object) {
		if(container.contains ? container.contains(object) || container == object : container.compareDocumentPosition(object) & 16)
			return true;
		return false;
	},
	
    getAbsolutePosition : function( element) {		
        if(!element) return {x:0,y:0};		
        var sTop = element.offsetTop,sLeft = element.offsetLeft;
        while( element = element.offsetParent ) { 
            if (( element.style.overflow != 'visible' && element.style.overflow != '' )  ) break;  
	        sTop += element.offsetTop; 
	        sLeft += element.offsetLeft; 
        }
        return {x:sLeft,y:sTop};
    },
    
    getRelativePosition : function( element) {
		if(!element) return {x:0,y:0};
        var sTop = element.offsetTop,sLeft = element.offsetLeft;
        while( element = element.offsetParent ) { 
            if (( element.style.overflow != 'visible' && element.style.overflow != '' ) || element.style.position == "absolute" || element.style.position == "relative") break;  
	        sTop += element.offsetTop; 
	        sLeft += element.offsetLeft; 
        }
        return {x:sLeft,y:sTop};
    },   
	
    getVisibleDocumentSize : function() {
        return {width:this.getDocumentElement().clientWidth,height:this.getDocumentElement().clientHeight};
    },
    
    getRealDocumentSize : function() {
        if(Hrcbc.Browser.isIE7())
            return {width:document.body.scrollWidth,height:document.body.scrollHeight};   
        else if(Hrcbc.Browser.isFirefox() || Hrcbc.Browser.isOpera())
            return {width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight};
        else 
            return {width:document.body.offsetWidth,height:document.body.offsetHeight};
    },
    
    getScrollPosition : function() {
		return {x : this.getDocumentElement().scrollLeft, y : this.getDocumentElement().scrollTop};
    },
    
    createStyleSheet : function() {
        var nStyle = document.createElement("style");        
        document.documentElement.appendChild(nStyle);
        return document.styleSheets.last();
    },
    
    getStyleSheet : function() {
        if(arguments.length == 0) 
            return (document.styleSheets.length>0) ? document.styleSheets[0] : this.createStyleSheet();
        else {
            if(!document.styleSheets[arguments[0]])
                document.styleSheets[arguments[0]] = this.createStyleSheet();
            return document.styleSheets[arguments[0]];
        }  
    },
    
    loadStyle : function( styleUrl) {
		if(!Hrcbc.$STYLES) Hrcbc.$STYLES = {};
		if (!Hrcbc.$STYLES[styleUrl]) {
			if (Hrcbc.$ISLOAD) {
				var style = document.createElement("link");
				style.setAttribute("rel", "stylesheet");
				style.setAttribute("type", "text/css");
				style.setAttribute("href", styleUrl);
				var parent = document.documentElement;
				var heads = document.getElementsByTagName("head");
				if (heads.length > 0) 
					parent = heads[0];
								parent.appendChild(style);
			}
			else 
				document.write("<link href=\"{0}\" type=\"text/css\" rel=\"stylesheet\" />".format(styleUrl));
			Hrcbc.$STYLES[styleUrl] = true;
		}		
    },
    
    addStyle : function( ruleName, cssText, index) {
		var styleSheet = Hrcbc.getStyleSheet();
		var rules = styleSheet.rules || styleSheet.cssRules;		
        if(this.$STYLES[ruleName]) {
			if(this.$STYLES[ruleName].cssText == cssText) return;
			var index = -1;
			if (this.$STYLES[ruleName].index < 0) {			
				for (var i = rules.length - 1; i >= 0; i--) {
					if (rules[i].selectorText == ruleName) {
						index = i;
						break;
					}
				}
			}
			else {
				index = this.$STYLES[ruleName].index;
			}
			if(index >=0) {
				if (styleSheet.deleteRule) 
					styleSheet.deleteRule(index);
				else 
					styleSheet.removeRule(index);
			}
		}
		this.$STYLES[ruleName] = {
			cssText: cssText
		};		
		index = Object.isNull(index) ? rules.length : index;		
		if(styleSheet.insertRule)
			this.$STYLES[ruleName].index = styleSheet.insertRule("{0}{{1}}".format(ruleName,cssText),index);			
		else
			this.$STYLES[ruleName].index = styleSheet.addRule(ruleName,cssText,index);
		
    },    
	
    setCookie : function( name, value, expires, path, domain, secure) {  
		var expdate = new Date();
		var argv = arguments;
		var argc = arguments.length;
		var expires = expires || null;
		var path = path || null;
		var domain = domain || null;
		var secure = secure == true ? true : false;
		if(expires!=null && expires>=0) 
			expdate.setTime(expdate.getTime() + ( expires * 1000 ));
		document.cookie = name + "=" + escape(((typeof(value)=="object") ? value.toJSONString() : value)) +((expires == null || expires < 0) ? ((expires==-1)?"; expires=-1":"") : ("; expires="+ expdate.toGMTString()))	+((path == null) ? "" : ("; path=" + path)) +((domain == null) ? "" : ("; domain=" + domain))	+((secure == true) ? "; secure" : "");	
	},
	
	getQueryString : function( key) {
	    key = key + "=";        
        if(window.location.search.length>0){
            begin = window.location.search.indexOf(key);
            if(begin != -1){
                begin += key.length;
                end = window.location.search.indexOf("&",begin);
                if(end == -1)
                    end = window.location.search.length;
                return unescape(window.location.search.substring(begin,end));
            }
            return null;
        }
        return null;
	},
	
    delCookie : function( name)   {
        var exp = new Date();
        exp.setTime (exp.getTime() - 1);
        var cval = this.getCookie(name);
        document.cookie = name + "=" + cval + "; expires="+ exp.toGMTString();
    },    
	
    getCookie : function( name) {
        var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
        if(arr != null) return unescape(arr[2]); else  return null;
    },
    
    getDocumentElement : function(){
		if(Hrcbc.Browser.isSafari())
			return document.body;       
        else if(Hrcbc.Browser.isOpera())
            return document.documentElement;
        else
            return (document.compatMode && document.compatMode == "BackCompat")? document.body:document.documentElement; 
    },	
	
    scrollToElement : function( element, ralativePos) {
        if(element) {
            var ePos = this.getAbsolutePosition(element); 
            if(ralativePos) {
                if(ralativePos.left) ePos.left += ralativePos.left;
                if(ralativePos.top) ePos.top += ralativePos.top;
            }
            window.scrollTo(ePos.left,ePos.top);
        }
    },	
    
    getMaxZOrder : function() {
        return ++this.$MAX_ZORDER;
    },
	Browser : {
		 name : null,			version : null,			mode : null,			
		getBrowserName : function() {
			var name  = this.name;
			switch(this.name) {			
				case "msie":
					name = "IE";
					break;
				default:
					name = name.toFirstUpper();
					break;
			}
			return name + " " + this.version;
		},
		
		getVersion : function() {
			return this.version;
		},

		isIE7: function() {
		    var ua = navigator.userAgent.toLowerCase();
		    return ua.indexOf("msie 7") > -1;
		},
	    
	    isIE: function() {
	        return this.name == "msie";
	    },
	    
	    isFirefox: function() {
	        return this.name == "firefox";
	    },
	    
	    isOpera: function() {
	       	return this.name == "opera";
	    },
	    
	    isNetscape: function() {
	        return this.name == "netscape";
	    },
	    
	    isSafari: function() {
	        return this.name == "safari";
	    }    
	},
	Xml : {
		
	    $XML_DOM_VERS : ["MSXML2.DOMDocument.6.0","MSXML2.DOMDocument.3.0"],   
	    
	    createDocument : function( rootNodeName) {
	        var xmlDoc = null;
	        if(window.ActiveXObject) {
	            for(var i=0; i<this.$XML_DOM_VERS.length; i++)  {
	                try {            
	                    xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
	                    this.$XML_DOM_VERS = [this.$XML_DOM_VERS[i]];
	                    break;
	                }catch(e){};
	            }
	        }
	        else xmlDoc = document.implementation.createDocument("","", null);        
	        if(!Hrcbc.Browser.isOpera())
	            xmlDoc.appendChild(xmlDoc.createProcessingInstruction("xml","version='1.0'"));  
	        if(typeof(rootNodeName) == "string") {
	            var root=xmlDoc.createElement(rootNodeName);
	            xmlDoc.appendChild(root);
	        }
	        return xmlDoc;
	    },    
		
	    serializeToString : function( sNode) {
	        var sXml = "";    
	        switch (sNode.nodeType) {
	            case 1: 
	                sXml = "<" + sNode.tagName;                
	                for (var i=0; i < sNode.attributes.length; i++) 
	                    sXml += " " + sNode.attributes[i].name + "=\"" + sNode.attributes[i].value + "\"";                
	                sXml += ">";                
	                for (var i=0; i < sNode.childNodes.length; i++)
	                    sXml += Hrcbc.Xml.serializeToString(sNode.childNodes[i]);                
	                sXml += "</" + sNode.tagName + ">";
	                break;                
	            case 3: 
	                sXml = sNode.nodeValue;
	                break;
	            case 4: 
	                sXml = "<![CDATA[" + sNode.nodeValue + "]]>";
	                break;
	            case 7: 
	                sXml = "<?" + sNode.nodevalue + "?>";
	                break;
	            case 8: 
	                sXml = "<!--" + sNode.nodevalue + "-->";
	                break;
	            case 9: 
	                for (var i=0; i < sNode.childNodes.length; i++)
	                    sXml += Hrcbc.Xml.serializeToString(sNode.childNodes[i]);                
	                break;                
	        }
	        return sXml;
	    },
	    
	    transformToText : function ( oXml, oXslt ) {
	        var result = null;
	        if (typeof XSLTProcessor != "undefined") {
	            var oProcessor = new XSLTProcessor();
	            oProcessor.importStylesheet(oXslt);        
	            var oResultDom = oProcessor.transformToDocument(oXml);
	            result = this.serializeToString(oResultDom);        
	            if (result.indexOf("<transformiix:result") > -1) 
	                result = result.substring(result.indexOf(">") + 1,result.lastIndexOf("<")); 
	        }
	        else if (window.ActiveXObject) {
	            result = oXml.transformNode(oXslt);
	        } 
	        if(result != null) 
	            result = result.replace(/<\?xml(.*?)\?>/,'');
	        return result;
	    },   
		
	    loadXML : function( sXml) {
	        var xmlDoc = this.createDocument();		
			try {
				xmlDoc.loadXML(sXml);
			}
			catch(e) {
				var domParser = new DOMParser();
	        	xmlDoc = domParser.parseFromString(sXml, "text/xml");			
			}
			return xmlDoc;        
	    },
		
		parseJSON : function( xml,xpath) {		
			if(typeof(xml) == "string") 
				xml = this.loadXML(xml);
			if(typeof(xml) != "object")	return null;
			if(xml.nodeType == 3) return xml.nodeValue;
			if(xml.nodeType != 1 && xml.nodeType != 9) return null;
			if(xpath) {
				var o = [];
				var xmlNodes = xml.selectNodes(xpath);
				for(var i=0; i<xmlNodes.length; i++) {
					var c = Hrcbc.Xml.parseJSON(xmlNodes[i]);
					if(c) o.push(c);
				}
				return o;
			}
			var o = new Object();
			var attributeCount = 0,childCount = 0;
			if (xml.nodeType == 1) {
				for (var i = 0; i < xml.attributes.length; i++) {				
					var attribute = xml.attributes[i];
					o[attribute.nodeName] = attribute.nodeValue;
					attributeCount++;
				}
			}
			for(var i=0;i<xml.childNodes.length; i++) {						
				var xmlNode = xml.childNodes[i];
				if (xmlNode.nodeType == 1) {
					var sameNodeCount = xml.selectNodes(xmlNode.nodeName);
					if (sameNodeCount.length > 1) {
						if (!o[xmlNode.nodeName]) 
							o[xmlNode.nodeName] = [];
						o[xmlNode.nodeName].push(Hrcbc.Xml.parseJSON(xmlNode));
					}
					else {
						o[xmlNode.nodeName] = Hrcbc.Xml.parseJSON(xmlNode);
					}
					childCount++;
				}
				else if(xmlNode.nodeType == 3 && xml.childNodes.length == 1) {
					o = xmlNode.nodeValue;
					childCount++;
					break;
				}
			}	
			if(attributeCount == 0 && childCount == 0) return "";				
			return o;
		}
	},
	AjaxMode : {
		XMLHttpRequest: 1,
    	IFrame: 2
	},
	AjaxRequest : function( asyncMode, ajaxMode) {	
		this.url = window.location.href;
		this.method = "POST";
		this.asyncMode = (asyncMode == undefined || asyncMode == null) ? true : asyncMode;
		this.ajaxMode = ajaxMode || Hrcbc.AjaxMode.XMLHttpRequest;
		this.request = null;
		this.responseText = "";
		this.responseXML = null;
		
		
		this.create = function() {				
			if(this.ajaxMode == Hrcbc.AjaxMode.XMLHttpRequest){
				if (window.XMLHttpRequest) {
					this.request = new XMLHttpRequest();
					return this.request;
				}
				with(Hrcbc.AjaxRequest){
					for(var i=0; i<$XMLHTTP_VERS.length; i++) {
						try {
	                        this.request = new ActiveXObject($XMLHTTP_VERS[i]);
	                    }
	                    catch(e) {}
	                    if(this.request) {
	                        $XMLHTTP_VERS = [$XMLHTTP_VERS[i]];
							return this.request;
	                    }
					}
				}
			}
								
			this.request = new Hrcbc.IframeRequest();
			return this.request;
		};
		this.abort = function() {
		   this.request.abort();
		   this.request = null;	   
		};
		
		this.send = function( url, method, data, headers, callback) {
			if(!this.request) this.create();
			if(url) this.url = url;
			if(method) this.method = method;
			if(callback && callback instanceof Function) {
				Hrcbc.Event.addEventListener(this,"complete",callback);
			}
			var _this = this; 
			if (this.asyncMode) {
				this.request.onreadystatechange = function(){
					if (_this.request.readyState == 4) {
						if (_this.request.status == 200 || _this.request.status == 0) {
							_this.responseText = _this.request.responseText;
							_this.responseXML = _this.request.responseXML;
							_this.complete(_this);
						}
						else 
							_this.fail(_this);
					}
				}
			}
			this.request.open(this.method,this.url,this.asyncMode);		
			if (!Class.exists("Hrcbc.IframeRequest") || !(this.request instanceof Hrcbc.IframeRequest)) {
				if (this.method.toLower() == "post") {
					this.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				}
				if(headers) {
					if(typeof(headers) == "string")
						headers = Array.parse(headers,";");
					for(var i=0; i<headers.length; i++) {
						var header = headers[i];
						if(typeof(headers[i]) == "string")
							header = header.split("=");
						if(header[0] && header[1])
							this.request.setRequestHeader(header[0],header[1]);
					}
				}
			}
			this.request.send(data || null);
			if(!this.asyncMode) {
				try
				{
					this.responseText = this.request.responseText;
					this.responseXML = this.request.responseXML;
					this.complete(this);
				}
				catch(e) {
					this.fail(e);
				}
			}	
		};	
		this.complete = function(){
			
		};
		this.fail = function() {
					};
	},
	IframeRequest : function(){	
		this.id = Hrcbc.Guid.newGuid().toString("n");
		this.form = null;
		this.method = "POST";
		this.url = window.location.href;
		this.asyncMode = true;
		this.readyState = 0;
		this.status = 0;
		this.responseText = "";
		this.responseXML = null;
		this.timer = null;	
		Hrcbc.IframeRequest.$REQUESTS[this.id] = this;	
		var _this = this;
		var setReadyState = function(readyState) {
			_this.readyState = readyState;
			if(_this.onreadystatechange) {
				_this.onreadystatechange();
			}
		};	
		var setStatus = function(status) {
			_this.status = status;
			if(_this.onreadystatechange) {
				_this.onreadystatechange();
			}
		};
		
		var html = "<iframe name=\"frame{0}\" id=\"frame{0}\" onload=\"Hrcbc.IframeRequest.$REQUESTS['{0}'].onload();\" style=\"height:0px;width:0px;margin:0px;padding:0px;border:0px\" frameborder=\"0\" src=\"about:blank\"></iframe>".format(this.id);
		if(Hrcbc.$ISLOAD) {
			var div = document.createElement("div");
			div.innerHTML = html;
			div.style.display = "none";
			document.body.appendChild(div);
		}
		else {
			document.write(html);
		}
		this.element = document.getElementById("frame"+this.id);
		
		this.onload = function() {
			if (this.readyState > 1 && this.readyState < 4) {
				try
				{
				    var _document = this.element.contentWindow.document;
				    if(_document.readyState && _document.readyState != "complete") return;			    
					this.responseText = _document.body.innerHTML;
					try
					{
						
						this.responseXML = Hrcbc.Xml.loadXML(this.responseText);
					}catch(e){}
					setStatus(200);	
					setReadyState(4);							
				}
				catch(e){}
			}
		};
		
		this.open = function( method, url, asyncMode) {		
			if(method) this.method = method;
			if(asyncMode) this.asyncMode = asyncMode;
			if(url) this.url = url;
			if (method.toLower() != "post") {
				if(this.form == null) {
					var formHtml = "<form name=\"form{0}\" id=\"form{0}\" method=\"POST\" style=\"height:0px;width:0px;margin:0px;padding:0px;\" target=\"frame{0}\" action=\"{1}\"></form>".format(this.id,this.url);
					if (Hrcbc.$ISLOAD) {
						var div = document.createElement("div");
						div.innerHTML = formHtml;
						div.style.display = "none";
						document.body.appendChild(div);
					}
					else {
						document.write(formHtml);
					}
					this.form = document.getElementById("form" + this.id);
				}
				else {
					this.form.setAttribute("target","frame" + this.id);
				}
			}
			setReadyState(1);
			setStatus(201);
		};
		this.abort = function() {
		    
		};
		
		this.send = function(data) {
			if(this.method.toLower() == "post" && this.form != null) {
				if(typeof(data) == "string") 
					data = Array.parse(data,";");
				for(var i=0; i<data.length; i++) {
					var item = typeof(data[i]) == "string" ? data[i].split("=") : data[i];
					if(!item[0]) continue;
					var input = document.createElement("input");
					input.setAttribute("type","hidden");
	                input.setAttribute("name",item[0]);
	                input.setAttribute("value", item[1]?item[1]:"");
	                this.form.appendChild(input);
				}
				this.form.submit();
			}
			else {
				this.element.setAttribute("src",this.url);
			}
			setReadyState(2);
		};
	},
	
	Event : {
			
	    getEvent : function() {		
			if(window.event) {			
				var oEvent = window.event;
				if (document.all) {
					if (oEvent.type == "mouseout") {
						oEvent.relatedTarget = oEvent.toElement;
					}
					else if (oEvent.type == "mouseover") {
						oEvent.relatedTarget = oEvent.fromElement;
					}
					oEvent.stopPropagation = function(){
						this.cancelBubble = true;
					};
				}
				return oEvent;	
			}
			var method = Hrcbc.Event.getEvent.caller;
			while(method != null) {
		        var arg = method.arguments[0];
		        if(arg)	{	
	                try {						
		                if(arg.constructor == Event || arg.constructor == MouseEvent )								
			                return arg;
			        }catch(e) { return null;}
		        }
		        method = method.caller;
	        }
	        return null;
		},
		
		cancelBubble : function( e) {
	        var ev = e || this.getEvent();
	        if (ev.preventDefault) { 
	            ev.preventDefault(); 
	            ev.stopPropagation(); 
	        } else { 
	            ev.cancelBubble = true; 
	        } 
	    },
		
		position : function( e) {
			var ev = e || this.getEvent();
					
			if(ev) 
				return {x : ev.clientX,y : ev.clientY};
			return {x:0,y:0};
		},
		
		target : function( e) {
			var ev = e || this.getEvent();
			return ev ? (ev.target || ev.srcElement) : null;
		},
		
		inject : function(object,eventName) {		
			if(!object.$INJECT_EVENT) object.$INJECT_EVENT = {};
			if (!object.$INJECT_EVENT[eventName]) {
				if (!(object[eventName] instanceof Function)) 
					object[eventName] = function(){};
				object[eventName] = object[eventName].callback(null, function(){
					Hrcbc.Event.invoke(object, eventName,arguments);
				});
				object.$INJECT_EVENT[eventName] = true;
			}		
		},
		
		invoke : function( object, eventName, args) {
			if (object.$EVENT_LISTENER && object.$EVENT_LISTENER[eventName]) {
				for (var i = 0; i < object.$EVENT_LISTENER[eventName].length; i++) 				
					object.$EVENT_LISTENER[eventName][i].apply(object,args);
			}
		},
		
		addEventListener : function( object, eventName, method, useCapture) {
			if(typeof(object) == "string") object = document.getElementById(object);
	        if(!object) return; 
			useCapture = useCapture || false;				
			if((object.attachEvent || object.addEventListener) && (!Object.isNull(object.nodeType) || window == object || document == object)) {
				if (eventName == "keypress" && (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || object.attachEvent))
	            	eventName = "keydown";
				if (object.addEventListener)             	
		            object.addEventListener(eventName, method, useCapture);
		        else if (object.attachEvent) 
		            object.attachEvent('on' + eventName, method);
			}
			else {			
				this.inject(object,eventName);
			}
			if(!object.$EVENT_LISTENER) object.$EVENT_LISTENER = {};
			if(!object.$EVENT_LISTENER[eventName]) object.$EVENT_LISTENER[eventName] = [];
			object.$EVENT_LISTENER[eventName].push(method);
		},
		
		removeEventListener : function( object, eventName, method, useCapture) {
			if(typeof(object) == "string") object = document.getElementById(object);
	        if(!object) return; 
			if(!eventName && object.$EVENT_LISTENER) {
				for(var p in object.$EVENT_LISTENER) {
					if(typeof(p) == "string" && !Object.isOriginal(p))
						Hrcbc.Event.removeEventListener(object,p,object.$EVENT_LISTENER[p],useCapture);
				}
				return;						
			}
			if(!method) return;
			useCapture = useCapture || false;
			if (object.attachEvent || object.addEventListener) {
				if (eventName == "keypress" && (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || object.attachEvent))
	            	eventName = "keydown";
				if (object.removeEventListener) 
		            object.removeEventListener(eventName, method, useCapture);	        
		        else if (object.detachEvent) 
		            object.detachEvent('on' + eventName, method);
			}
			if(object.$EVENT_LISTENER && object.$EVENT_LISTENER[eventName])	
				object.$EVENT_LISTENER[eventName].remove(method);
		},
		
		addDispatcher : function( object) {
			if(!object.$ISDISPATCHER){
				object.addEventListener = function( eventName, method, useCapture){
					Hrcbc.Event.addEventListener(this,eventName,method,useCapture);
				};
				object.removeEventListener = function( eventName, method, useCapture){
					Hrcbc.Event.removeEventListener(this,eventName,method,useCapture);
				};
				object.$ISDISPATCHER = true;
			}
		}
	},
	
	Guid : function() {
		this.guid = new Array(5);
		
		this.toString = function( format) {
			format = format || "D";
			var s = "";
			if(/[Nn]/.test(format)) {
				s = this.guid.join("");
			} 		
			else {
				s = this.guid.join("-");
				if(/[Bb]/.test(format)) 
					s = "{" + s + "}";
				else if(/[Pp]/.test(format))
					s = "(" + s + ")";
			}
			return /[A-Z]/.test(format) ? s.toUpper() : s.toLower();
		};	
		var args = Array.parse(arguments);
		if(args.length == 5 && args.join("").length == 32 && args[0].length == 8 && args[1].length == 4 && args[2].length == 4 && args[3].length == 4 && args[4].length == 12) {
			this.guid = args;
		}
		else if(args.length == 1 && typeof(args[0]) == "string" && args[0].length.isIn([32,36,38])) {
			var s = args[0].replace(/{|}|\(|\)|-/g,"");
			this.guid[0] = s.substring(0,8);
			this.guid[1] = s.substring(8,12);
			this.guid[2] = s.substring(12,16);
			this.guid[3] = s.substring(16,20);
			this.guid[4] = s.substring(20,32);
		}
		else {
		    
			this.guid[0] = "0".repeat(8);
			this.guid[1] = "0".repeat(4);
			this.guid[2] = "0".repeat(4);
			this.guid[3] = "0".repeat(4);
			this.guid[4] = "0".repeat(12);
		}
	},
	DateTime : {
		
	    $MONTH_DAYS: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
	    
	    $LUNARINFO: [
			0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,
			0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977,
			0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970,
			0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950,
			0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557,
			0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5d0, 0x14573, 0x052d0, 0x0a9a8, 0x0e950, 0x06aa0,
			0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0,
			0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b5a0, 0x195a6,
			0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570,
			0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0,
			0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5,
			0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930,
			0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530,
			0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45,
			0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0
		],
	    
	    $GAN: ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"],
	    
	    $ZHI: ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"],
	    
	    $SOLARTERM: ["小寒", "大寒", "立春", "雨水", "惊蛰", "春分", "清明", "谷雨", "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪", "冬至"],
	    
	    $TERMINFO: [0, 21208, 42467, 63836, 85337, 107014, 128867, 150921, 173149, 195551, 218072, 240693, 263343, 285989, 308563, 331033, 353350, 375494, 397447, 419210, 440795, 462224, 483532, 504758],
	    
	    $ANIMALS: ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"],
	    
	    $CNDAYNUMS: ['日', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'],
	    $CNDAYNUMS2: ['初', '十', '廿', '卅', ' '],
	    
	    $FESTIVALS: [
			"0101*新年元旦", "0202 世界湿地日", "0207 国际声援南非日", "0210 国际气象节", "0214 情人节",
			"0301 国际海豹日", "0303 全国爱耳日", "0308 国际妇女节", "0312 植树节 孙中山逝世纪念日", "0314 国际警察日",
			"0315 国际消费者权益日", "0317 中国国医节 国际航海日", "0321 世界森林日 消除种族歧视国际日", "0321 世界儿歌日", "0322 世界水日",
			"0323 世界气象日", "0324 世界防治结核病日", "0325 全国中小学生安全教育日", "0330 巴勒斯坦国土日", "0401 愚人节 全国爱国卫生运动月(四月) 税收宣传月(四月)",
			"0407 世界卫生日", "0422 世界地球日", "0423 世界图书和版权日", "0424 亚非新闻工作者日", "0501 国际劳动节",
			"0504 中国五四青年节", "0505 碘缺乏病防治日", "0508 世界红十字日", "0512 国际护士节", "0515 国际家庭日",
			"0517 世界电信日", "0518 国际博物馆日", "0520 全国学生营养日", "0523 国际牛奶日", "0531 世界无烟日",
			"0601 国际儿童节", "0605 世界环境日", "0606 全国爱眼日", "0617 防治荒漠化和干旱日", "0623 国际奥林匹克日",
			"0625 全国土地日", "0626 国际反毒品日", "0701 中国共产党建党日 世界建筑日", "0702 国际体育记者日", "0707 中国人民抗日战争纪念日",
			"0711 世界人口日", "0730 非洲妇女日", "0801 中国建军节", "0808 中国男子节(爸爸节)", "0815 日本正式宣布无条件投降日",
			"0908 国际扫盲日 国际新闻工作者日", "0910 教师节", "0914 世界清洁地球日", "0916 国际臭氧层保护日", "0918 九·一八事变纪念日",
			"0920 国际爱牙日", "0927 世界旅游日", "1001*国庆节", "1001 国际音乐日", "1002 国际和平与民主自由斗争日",
			"1004 世界动物日", "1008 全国高血压日", "1008 世界视觉日", "1009 世界邮政日 万国邮联日", "1010 辛亥革命纪念日 世界精神卫生日",
			"1013 世界保健日 国际教师节", "1014 世界标准日", "1015 国际盲人节(白手杖节)", "1016 世界粮食日", "1017 世界消除贫困日",
			"1022 世界传统医药日", "1024 联合国日 世界发展信息日", "1031 世界勤俭日", "1107 十月社会主义革命纪念日", "1108 中国记者日",
			"1109 全国消防安全宣传教育日", "1110 世界青年节", "1111 国际科学与和平周(本日所属的一周)", "1112 孙中山诞辰纪念日", "1114 世界糖尿病日",
			"1117 国际大学生节 世界学生节", "1121 世界问候日 世界电视日", "1129 国际声援巴勒斯坦人民国际日", "1201 世界艾滋病日", "1203 世界残疾人日",
			"1205 国际经济和社会发展志愿人员日", "1208 国际儿童电视日", "1209 世界足球日", "1210 世界人权日", "1212 西安事变纪念日",
			"1213 南京大屠杀(1937年)纪念日！紧记血泪史！", "1221 国际篮球日", "1224 平安夜", "1225 圣诞节", "1229 国际生物多样性日"
		],
	    
	    $WEST_FESTIVALS: [
			"0520 母亲节", "0630 父亲节", "1144 感恩节"
		],
	    
	    $CN_FESTIVALS: [
			"0101*春节", "0115 元宵节", "0202 龙抬头节", "0323 妈祖生辰 (天上圣母诞辰)", "0505 端午节",
			"0707 七七中国情人节", "0815 中秋节", "0909 重阳节", "1208 腊八节", "1223 过小年", "0100*除夕"
		],
	    
	    getDays: function(year, month) {
	        if (month == 1) 	            return (((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) ? 29 : 28);
	        else
	            return this.$MONTH_DAYS[month];
	    },
	    
	    getCNDays: function(year, month) {
	        return ((this.$LUNARINFO[year - 1900] & (0x10000 >> month)) ? 30 : 29);
	    },
	    
	    getCNYearDays: function(y) {
	        var i, sum = 348;
	        for (i = 0x8000; i > 0x8; i >>= 1)
	            sum += (this.$LUNARINFO[y - 1900] & i) ? 1 : 0;
	        return (sum + this.getLeapDays(y));
	    },
	    
	    getLeapMonth: function(y) {
	        return (this.$LUNARINFO[y - 1900] & 0xf);
	    },
	    
	    getLeapDays: function(y) {
	        if (this.getLeapMonth(y))
	            return ((this.$LUNARINFO[y - 1900] & 0x10000) ? 30 : 29);
	        else return (0);
	    },
	    
	    getGanZhi: function(n) {
	        return this.$GAN[n % 10] + this.$ZHI[n % 12];
	    },
	    
	    getSolarTerm: function(year, n) {
	        var offDate = new Date((31556925974.7 * (year - 1900) + this.$TERMINFO[n] * 60000) + Date.UTC(1900, 0, 6, 2, 5));
	        return offDate.getUTCDate();
	    },
	    
	    getCNYearName: function(year) {
	        var sYear = String(year), yearName = "";
	        for (var i = 0; i < sYear.length; i++)
	            yearName += sYear.charAt(i) == '0' ? '零' : this.$CNDAYNUMS[parseInt(sYear.charAt(i))];
	        return yearName;
	    },
	    
	    getCNMonthName: function(month) {
	        return month > 10 ? ('十' + this.$CNDAYNUMS[month - 10]) : this.$CNDAYNUMS[month];
	    },
	    
	    getCNDayName: function(day) {
	        switch (day) {
	            case 10: return '初十';
	            case 20: return '二十';
	            case 30: return '三十';
	            default:
	                return this.$CNDAYNUMS2[Math.floor(day / 10)] + this.$CNDAYNUMS[day % 10];
	        }
	    },
	    
	    getFestival: function(month, day) {
	        for (var i = 0; i < this.$FESTIVALS.length; i++) {
	            if (this.$FESTIVALS[i].match(/^(\d{2})(\d{2})([\s\*])(.+)$/)) {
	                if (parseInt(RegExp.$1) == month && parseInt(RegExp.$2) == day)
	                    return RegExp.$4;
	            }
	        }
	        return "";
	    },
	    
	    getWestFestival: function(month, day) {
	        for (var i = 0; i < this.$WEST_FESTIVALS.length; i++) {
	            if (this.$WEST_FESTIVALS[i].match(/^(\d{2})(\d{2})([\s\*])(.+)$/)) {
	                if (parseInt(RegExp.$1) == month && parseInt(RegExp.$2) == day)
	                    return RegExp.$4;
	            }
	        }
	        return "";
	    },
	    
	    getCNFestival: function(month, day) {
	        for (var i = 0; i < this.$CN_FESTIVALS.length; i++) {
	            if (this.$CN_FESTIVALS[i].match(/^(\d{2})(\d{2})([\s\*])(.+)$/)) {
	                if (parseInt(RegExp.$1) == month && parseInt(RegExp.$2) == day)
	                    return RegExp.$4;
	            }
	        }
	        return "";
	    },
	    
	    getCNDate: function(oDate) {
	        var i, leap = 0, temp = 0, cnDate = {};
	        var offset = (oDate - new Date(1900, 0, 31)) / 86400000;
	        for (i = 1900; i < 2050 && offset > 0; i++) {
	            temp = this.getCNYearDays(i);
	            offset -= temp;
	        }
	        if (offset < 0) {
	            offset += temp;
	            i--;
	        }
	        cnDate.year = i;
	        leap = this.getLeapMonth(i); 	        cnDate.isLeap = false;
	        for (i = 1; i < 13 && offset > 0; i++) {
	            if (leap > 0 && i == (leap + 1) && cnDate.isLeap == false) { 	                --i;
	                cnDate.isLeap = true;
	                temp = this.getLeapDays(cnDate.year);
	            } else temp = this.getCNDays(cnDate.year, i);
	            if (cnDate.isLeap == true && i == (leap + 1)) 	                cnDate.isLeap = false;
	            offset -= temp;
	        }
	        if (offset == 0 && leap > 0 && i == leap + 1) {
	            if (!cnDate.isLeap) {
	                cnDate.isLeap = true;
	                --i;
	            } else cnDate.isLeap = false;
	        }
	        if (offset < 0) {
	            offset += temp;
	            --i;
	        }
	        cnDate.month = i;
	        cnDate.day = offset + 1;
	        return cnDate;
	    },
	    
	    parse: function(dateVal, dateTimeFormat) {
	        var format = dateTimeFormat || "yyyy-MM-dd hh:mm:ss";
	        var matchYear = format.match(/(y+)/);
	        var matchMonth = format.match(/(M+)/);
	        var matchDate = format.match(/(d+)/);
	        var matchHour = format.match(/(h+)/);
	        var matchMinute = format.match(/(m+)/);
	        var matchSecond = format.match(/(s+)/);
	        var yearValue = 2000, monthValue = 0, dateValue = 1, hourValue = 0, minuteValue = 0, secondValue = 0;
	        if (matchYear)
	            yearValue = parseInt(dateVal.substr(matchYear.index, matchYear[1].length) || "2000", 10);
	        if (matchMonth)
	            monthValue = parseInt(dateVal.substr(matchMonth.index, matchMonth[1].length) || "1", 10) - 1;
	        if (matchDate)
	            dateValue = parseInt(dateVal.substr(matchDate.index, matchDate[1].length) || "1", 10);
	        if (matchHour)
	            hourValue = parseInt(dateVal.substr(matchHour.index, matchHour[1].length) || "0", 10);
	        if (matchMinute)
	            minuteValue = parseInt(dateVal.substr(matchMinute.index, matchMinute[1].length) || "0", 10);
	        if (matchSecond)
	            secondValue = parseInt(dateVal.substr(matchSecond.index, matchSecond[1].length) || "0", 10);
	        return new Date(yearValue, monthValue, dateValue, hourValue, minuteValue, secondValue);
	    }
	}
});

(function(){
	var agent = window.navigator.userAgent.toLowerCase();
	Hrcbc.Browser.version = (agent.match(/.+(?:pe6?|or|ox|it|ra|ie|rv)[\/: ]([\d.]+)/) || [])[1],
	Hrcbc.Browser.name	= /(netscape|firefox|opera|msie|safari|konqueror)/.test(agent) ? RegExp.$1 : (/webkit/.test(agent) ? "safari" : (/mozilla/.test(agent) ? "mozilla" : "unknown")),
	Hrcbc.Browser.mode = document.compatMode == "CSS1Compat" ? "standard" : "quirk";
})();

Hrcbc.AjaxRequest.extend({
	$AJAX_REQUESTS : [],
	
    $XMLHTTP_VERS : ["Microsoft.XMLHTTP","Msxml2.XMLHTTP","MSXML2.XmlHttp.3.0","Msxml2.XMLHTTP.4.0","MSXML2.XmlHttp.6.0"],
	 
	createRequest : function( asyncMode, ajaxMode){
		this.$AJAX_REQUESTS.push(new Hrcbc.AjaxRequest(asyncMode,ajaxMode));
		return this.$AJAX_REQUESTS.last();		
	},
	
	getText : function( url, asyncMode, callback, ajaxMode) {
		var request = this.createRequest((asyncMode == undefined || asyncMode == null) ? false : asyncMode,ajaxMode);
		request.send(url,"GET",null,null,callback);
		if(asyncMode == true) return request;
		return request.responseText;
	},
	
	getXml : function( url, asyncMode, callback){
		var request = this.createRequest((asyncMode == undefined || asyncMode == null) ? false : asyncMode);
		request.send(url,"GET",null,null,callback);
		if(asyncMode == true) return request;
		return request.responseXML;
	},
	
	sendData : function( url, data, callback, asyncMode, headers) {
		var request = this.createRequest((asyncMode == undefined || asyncMode == null) ? true : asyncMode);
		request.send(url,"POST",data,headers,callback);
		return request;
	} 	
});

Hrcbc.Guid.extend({
    newGuid : function() {
	    var f1 = Math.random()*10000000000000000;        
        var f5 = Math.random()*10000000000000000;
        var t = new Date();
        var y = String(t.getFullYear());
        var h = t.getHours() < 10 ? ("0" + String(t.getHours())) : String(t.getHours());
        var m = t.getMinutes() < 10 ? ("0" + String(t.getMinutes())) : String(t.getMinutes());
        var s = t.getSeconds() < 10 ? ("0" + String(t.getSeconds())) : String(t.getSeconds());
        var ms = String(t.getMilliseconds());
        if(t.getMilliseconds() < 10) ms = "00" + String(t.getMilliseconds());
        if(t.getMilliseconds() < 100) ms = "0" + String(t.getMilliseconds());
        var f2 = m.substr(0,1) + ms.substr(2,1) + y.substr(2,1) + m.substr(1,1);
        var f3 = y.substr(3,1) + s.substr(0,1) + t.getMonth().toString(16) + s.substr(1,1);
        var f4 = h.substr(0,1) + ms.substr(0,1) + h.substr(1,1) + ms.substr(1,1);
	    return new Hrcbc.Guid(f1.toString(16).substr(0,8),f2,f3,f4,f5.toString(16).substr(0,12));
	}
});

Hrcbc.onload(function() {
    Hrcbc.$ISLOAD = true;
});

window.trace = function(message){
	Hrcbc.trace(message);
};



 
if(Hrcbc.Browser.isFirefox() || Hrcbc.Browser.isNetscape()) {
	var setOuterHTML = function(sHTML){
        var r=this.ownerDocument.createRange();
        r.setStartBefore(this);
        var df=r.createContextualFragment(sHTML);
        this.parentNode.replaceChild(df,this);
        return sHTML;
    };
	var getOuterHTML = function(){
        var attr;
        var attrs=this.attributes;
        var str="<"+this.tagName.toLowerCase();
        for(var i=0;i<attrs.length;i++){
            attr=attrs[i];
            if(attr.specified)   str+=" "+attr.name+'="'+attr.value+'"';
        }
        if(!this.canHaveChildren)  return str+">";
        return str+">"+this.innerHTML+"</"+this.tagName.toLowerCase()+">";
    };
	var getCanHaveChildren = function(){
		switch (this.tagName.toLowerCase()) {
			case "area":
			case "base":
			case "basefont":
			case "col":
			case "frame":
			case "hr":
			case "img":
			case "br":
			case "input":
			case "isindex":
			case "link":
			case "meta":
			case "param":
				return false;
		}
		return true;
	};	
    HTMLElement.prototype.__defineSetter__("outerHTML",setOuterHTML);
    HTMLElement.prototype.__defineGetter__("outerHTML",getOuterHTML);  
	HTMLElement.prototype.__defineGetter__("canHaveChildren",getCanHaveChildren);
	HTMLHtmlElement.prototype.__defineSetter__("outerHTML",setOuterHTML);    
	HTMLHtmlElement.prototype.__defineGetter__("outerHTML",getOuterHTML);
	HTMLHtmlElement.prototype.__defineGetter__("canHaveChildren",getCanHaveChildren);
}


if(Hrcbc.Browser.isFirefox() || Hrcbc.Browser.isNetscape()) {
    CSSStyleSheet.prototype.addRule = function(selectorText,cssText,index){
        return this.insertRule("{0}{{1}}".format(selectorText,cssText),index);
    }
    CSSStyleSheet.prototype.removeRule = CSSStyleSheet.prototype.deleteRule;
}



if( document.implementation.hasFeature("XPath", "3.0") && typeof(window.opera)!="object") {    
    XMLDocument.prototype.selectNodes = function( cXPathString, xNode) {
        if( !xNode ) { xNode = this; } 
        var oNSResolver = this.createNSResolver(this.documentElement) ;
        var aItems = this.evaluate(cXPathString, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
        var aResult = [];
        for( var i = 0; i < aItems.snapshotLength; i++)
            aResult.push(aItems.snapshotItem(i));   
        return aResult;
    }
    Element.prototype.selectNodes = function( cXPathString) {
        if(this.ownerDocument.selectNodes) 
            return this.ownerDocument.selectNodes(cXPathString, this);
        else
            return [];
    }
    XMLDocument.prototype.selectSingleNode = function( cXPathString, xNode) {
        if( !xNode ) { xNode = this; } 
        var xItems = this.selectNodes(cXPathString, xNode);
        if( xItems.length > 0 )
            return xItems[0];
        else
            return null;
    }
    Element.prototype.selectSingleNode = function( cXPathString) {    
        if(this.ownerDocument.selectSingleNode)
            return this.ownerDocument.selectSingleNode(cXPathString, this);
        else
            return [];
    }
}

Class.register("Hrcbc.Calendar",function(year,month) {
	var now = new Date(),cYear,cMonth,cDay;	
	var firstDate  = new Date(year || now.getFullYear(),(Object.isNull(month) || type(month) != "number") ? now.getMonth() : month,1,0,0,0);
	this.year = firstDate.getFullYear();
	this.month = firstDate.getMonth();
	this.length = Hrcbc.DateTime.getDays(this.year,this.month);
	this.firstWeek = firstDate.getDay();
	this.animal = Hrcbc.DateTime.$ANIMALS[(this.year-4)%12];			if(this.month<2) cYear = this.year - 1900 + 36 - 1;
   	else cYear = this.year - 1900 + 36;	
   	var term2= Hrcbc.DateTime.getSolarTerm(this.year,2);
   	var firstNode = Hrcbc.DateTime.getSolarTerm(this.year,this.month*2);
   	cMonth = (this.year-1900)*12+this.month+12;
   	var dayCyclical = Date.UTC(this.year,this.month,1,0,0,0,0)/86400000+25567+10;
	for(var i=0; i< this.length; i++) {		
		var cnDate = Hrcbc.DateTime.getCNDate(new Date(this.year,this.month,i+1));
		if(this.month==1 && (i+1)==term2) cYear = this.year-1900+36;
      	if((i+1)==firstNode) cMonth = (this.year-1900)*12+this.month+13;
      	cDay = dayCyclical+i;
		this[i] = {
			year : this.year,				month : this.month,				day : i + 1,					week : (this.firstWeek + i) % 7,				cnWeek : Hrcbc.DateTime.$CNDAYNUMS[(this.firstWeek + i) % 7],				cnYear : cnDate.year,				cnMonth : cnDate.month,				cnDay : cnDate.day, 				cnYearName : Hrcbc.DateTime.getCNYearName(cnDate.year),
			cnMonthName : Hrcbc.DateTime.getCNMonthName(cnDate.month),
			cnDayName : Hrcbc.DateTime.getCNDayName(cnDate.day),
			cYear : cYear,						cMonth : cMonth,					cDay : cDay,						cYearName : Hrcbc.DateTime.getGanZhi(cYear),
			cMonthName : Hrcbc.DateTime.getGanZhi(cMonth),
			cDayName : Hrcbc.DateTime.getGanZhi(cDay),
			isLeap : cnDate.isLeap,				solarTerm : '',						isToday : false,					festival : Hrcbc.DateTime.getFestival(this.month+1,i+1),  			westFestival : Hrcbc.DateTime.getWestFestival(this.month+1,i+1),				cnFestival : Hrcbc.DateTime.getCNFestival(cnDate.month,cnDate.day) 		};
	}
	var sm1 = Hrcbc.DateTime.getSolarTerm(this.year, this.month*2)-1;
    var sm2 = Hrcbc.DateTime.getSolarTerm(this.year, this.month*2+1)-1;
	this[sm1].solarTerm = Hrcbc.DateTime.$SOLARTERM[this.month*2];			this[sm2].solarTerm = Hrcbc.DateTime.$SOLARTERM[this.month*2+1];		if(this.year == now.getFullYear() && this.month == now.getMonth()) 
    	this[now.getDate()-1].isToday = true;
});

Class.register("Hrcbc.Validate",{
$ISHTML: /^(<(\w+)([\s]*(.|\n)*)?>(.|\n|\r)*<\/\2>)|(<.*\/>)$/i, $ISURL: /(\w+):\/\/([^\/:]+)(:\d*)?([^# ]*)/, $ISXML: /^(<\?xml([\s]*(.|\n)*)?\?>)?\s*((<(\w+)([\s]*(.|\n)*)?>(.|\n|\r)*<\/\6>)|(<.*\/>)){1,1}\s*$/, $ISEMAIL: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, $ISMOBILE: /^(13\d{9}|159\d{8}|153\d{8}|158\d{8}|150\d{8}|159\d{8}|188\d{8})$/, $ISPHONE: /(^[0-9]{3,4}\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^[0-9]{3,4}\-[0-9]{3,8}\-[0-9]{1,8})/, $ISNUMERIC: /^(-|\+)?\d+(\.\d+)?$/, $ISPOSITIVE: /^\d+(\.\d+)?$/, $ISINTEGER: /^(-|\+)?\d+$/, $ISSIGNLESSINTEGER: /^\d+$/, $HASVALUE: /[\S]/,
	$VALIDATORS : {},
	
	isHtml : function( s) {		
		return Hrcbc.Validate.$ISHTML.test(s);
	},
	
	isUrl : function( s) {
		return Hrcbc.Validate.$ISURL(s);
	},
	
	isXml : function( s) {
		return Hrcbc.Validate.$ISXML.test(s);
	},
	
	isEmail : function( s) {
		return Hrcbc.Validate.$ISEMAIL.test(s);
	},
	
	isMobile : function( s) {
		return Hrcbc.Validate.$ISMOBILE.test(s);
	},
	
	isPhone : function( s) {
		return Hrcbc.Validate.$ISPHONE.test(s);
	},
	
	hasValue : function( s) {
		if(Object.isNull(s)) return false;
		return Hrcbc.Validate.$HASVALUE.test(s);
	},
	
	isNumeric : function( s) {
		return Hrcbc.Validate.$ISNUMERIC.test(s);
	},
	
	isPositive : function( s){
		return Hrcbc.Validate.$ISPOSITIVE.test(s);
	},
	
	isInteger : function( s) {
		return Hrcbc.Validate.$ISINTEGER.test(s);
	},
	
	isSignlessInteger : function( s) {
		return Hrcbc.Validate.$ISSIGNLESSINTEGER.test(s);
	},
	
	getMethod : function( datatype) {
		switch(datatype) {
			case "int":
				return Hrcbc.Validate.isInteger; 
			case "uint":
				return Hrcbc.Validate.isSignlessInteger; 
			case "number":
				return Hrcbc.Validate.isNumeric; 
			case "positive":
				return Hrcbc.Validate.isPositive;
			case "phone":
				return Hrcbc.Validate.isPhone;
			case "mobile":
				return Hrcbc.Validate.isMobile;
			case "email":
				return Hrcbc.Validate.isEmail;
			case "string":
			default:
				return Hrcbc.Validate.hasValue;
		}
	},
	
	add : function( validator) {
	    var groupName =  validator.groupName;      
        if(!this.$VALIDATORS[groupName])
            this.$VALIDATORS[groupName] = [];        
        this.$VALIDATORS[groupName].push(validator); 
	},
	
	isValid : function( groupName, itemValidated) {
        var isValid = true;   
		var object = Hrcbc.Event.target();            
        if(object) {
            var isCausesValidation = object.getAttribute("CausesValidation");                       
            if(isCausesValidation == "false") return true;
        }
        if(groupName && !groupName.isEmpty()) {
            if(!this.$VALIDATORS[groupName]) return isValid;
            for(var i=0; i<this.$VALIDATORS[groupName].length; i++) {
                if(!this.$VALIDATORS[groupName][i].validate()) {
                    isValid = false;
                    if(itemValidated) itemValidated.apply(this.$VALIDATORS[groupName][i]);
                                    }
            }
        }
        else {
            for(var v in this.$VALIDATORS) {              
                if(!(this.$VALIDATORS[v] instanceof Array)) continue;
                for(var i = 0; i< this.$VALIDATORS[v].length; i++ ) {
                    if(!this.$VALIDATORS[v][i].validate()) {
                        isValid = false;
                        if(itemValidated) itemValidated.apply(this.$VALIDATORS[v][i]);
                                            }            
                }
            }
        }
        return isValid;
    }    
});



Class.load("Hrcbc.Validate");
Class.load("Hrcbc.Controls.Validator");

Class.load("Hrcbc.Controls.FileUploader");

Class.register("Hrcbc.WebForm", function(args) {
    this.extend(args, true);
    this.inited = false;
    this.init = function() {
        if (this.inited) return;
        if (this.form && typeof (this.form) == "string")
            this.form = document.getElementById(this.form);
        this.inited = true;
    };
    
    this.analyze = function() {
        this.init();
        if (this.form && typeof (this.form) == "object") {
            var submits = Hrcbc.selectNodes(this.form, "//*[@ctype=submit]");
            for (var i = 0; i < submits.length; i++)
                this.addSubmitButton(submits[i]);
            var fileInputs = Hrcbc.selectNodes(this.form, "//input[@type=file]");
            for (var i = 0; i < fileInputs.length; i++)
                this.addFileInput(fileInputs[i]);
            var validators = Hrcbc.selectNodes(this.form, "//*[@ctype=validator]");
            for (var i = 0; i < validators.length; i++)
                this.addValidator(validators[i]);
        }
    };
    
    this.addFileInput = function(fileInput) {
        if (!fileInput || Object.getAttribute(fileInput, "isInited") == "true" || Object.getAttribute(fileInput, "IsAjaxMode") == "false") return;
        var uploader = new Hrcbc.Controls.FileUploader(fileInput, {
            autoSubmit: Object.getAttribute(fileInput, "autoSubmit") || false,
            name: Object.getAttribute(fileInput, "name"),
            action: Object.getAttribute(fileInput, "postUrl") || Hrcbc.defaultUploadUrl,
            progressUrl: Object.getAttribute(fileInput, "progressUrl") || Hrcbc.defaultUploadProgressUrl,
            progress: String(Object.getAttribute(fileInput, "progress")).parseJSON()
        });
        this.addUploader(uploader);
        Object.setAttribute(uploader, "isInited", "true");
    };
    
    this.addUploader = function(uploader) {
        if (!this.$UPLOADERS) this.$UPLOADERS = [];
        this.$UPLOADERS.push(uploader);
    };
    
    this.addValidator = function(validator) {
        if (!validator || Object.getAttribute(validator, "isInited") == "true") return;
        var controlToValidate = Object.getAttribute(validator, "controlToValidate");
        var eventName = String(Object.getAttribute(validator, "eventName")).parseJSON();
        var validateMethod = String(Object.getAttribute(validator, "validateMethod")).parseJSON();
        for (var i = 0; i < this.$UPLOADERS.length; i++) {
            var uploader = this.$UPLOADERS[i];
            if (uploader.element.id == controlToValidate) {
                controlToValidate = uploader.fileInput;
                eventName = ["change"];
                if (Object.getAttribute(validator, "extensions")) {
                    var extensions = String(Object.getAttribute(validator, "extensions")).toLowerCase().split("|");
                    validateMethod = function(fileName) {
                        var extension = fileName.substring(fileName.lastIndexOf("."), fileName.length);
                        uploader.enableSubmit = extension.toLowerCase().isIn(extensions);
                        return uploader.enableSubmit;
                    };
                }
            }
        };
        var regexp = null;
        if (Object.getAttribute(validator, "regexp"))
            regexp = String(Object.getAttribute(validator, "regexp")).parseRegexp();
        Hrcbc.Validate.add(new Hrcbc.Controls.Validator(validator, {
            groupName: Object.getAttribute(validator, "validateGroup") || Object.getAttribute(this.form, "validateGroup") || "default",
            object: controlToValidate,
            description: Object.getAttribute(validator, "description"),
            rightMessage: Object.getAttribute(validator, "rightMessage"),
            errorMessage: Object.getAttribute(validator, "errorMessage"),
            controlMessage: new Hrcbc.Controls.Control(validator),
            eventName: eventName,
            attributeName: Object.getAttribute(validator, "attributeName"),
            groupName: Object.getAttribute(validator, "groupName"),
            isNullable: Object.getAttribute(validator, "isNullable") == "true",
            isAlert: Object.getAttribute(validator, "isAlert") == "true",
            enableSkin: Object.getAttribute(validator, "enableSkin") || true,
            rightCssClass: Object.getAttribute(validator, "rightCssClass"),
            errorCssClass: Object.getAttribute(validator, "errorCssClass"),
            cssClass: Object.getAttribute(validator, "cssClass"),
            regexp: regexp,
            method: validateMethod,
            datatype: Object.getAttribute(validator, "datatype")
        }));
        Object.setAttribute(validator, "isInited", "true");
    };
    
    this.addSubmitButton = function(submitButton) {
        if (!submitButton || Object.getAttribute(submitButton, "isInited") == "true") return;
        var _this = this;
        Hrcbc.Event.addEventListener(submitButton, "click", function() {
            if (Hrcbc.Validate.isValid(submitButton.groupName || _this.form.groupName))
                _this.submit(Object.getAttribute(submitButton, "isAjaxMode"), Object.getAttribute(submitButton, "url"), Object.getAttribute(submitButton, "method"));
        }, false);
        Object.setAttribute(submitButton, "isInited", "true");
    };
    
    this.submit = function(isAjaxMode, url, method, headers) {
        if (!this.form) return;
        this.isAjaxMode = Object.isNull(isAjaxMode) ? (Object.isNull(this.isAjaxMode) ? (Object.getAttribute(this.form, "isAjaxMode") == "true" || false) : this.isAjaxMode) : isAjaxMode;
        this.url = url || this.url || Object.getAttribute(this.form, "action") || window.location.href;
        this.method = method || this.method || Object.getAttribute(this.form, "method") || "post";
        this.headers = headers || this.headers;
        if (this.isAjaxMode) {
            var items = [];
            for (var i = 0; i < this.$UPLOADERS.length; i++) {
                var uploader = this.$UPLOADERS[i];
                if (!uploader.isAjaxUpload || (uploader.status && uploader.status == "uploading")) continue;
                if (uploader.status && uploader.status == "complete") {
                    items.push("{0}={1}".format(uploader.name, uploader.data.FileList[0].ServerFileName));
                    continue;
                };
                var _this = this;
                uploader.submit(null, null, function() {
                    _this.submit();
                });
                return;
            };
            var elements = Array.parse(this.form.elements);
            elements.remove.apply(elements, Hrcbc.selectNodes("//*[@dataField=false]"));
            elements = elements.concat(Hrcbc.selectNodes("//*[@dataField=true]"));
            for (var i = 0; i < elements.length; i++) {
                var e = elements[i];
                var isUploader = false;
                for (var j = 0; j < this.$UPLOADERS.length; j++) {
                    if (this.$UPLOADERS[j].element == e) {
                        isUploader = true;
                        break;
                    }
                };
                if (isUploader) continue;
                var value = Object.getAttribute(e, Object.getAttribute(e, "valueAttribute") || "value");
                items.push("{0}={1}".format(Object.getAttribute(e, "name"), value.replaceAll("&", "%26")));
            }
            var request = new Hrcbc.AjaxRequest(this.asyncMode, this.ajaxMode);
            request.send(this.url, this.method, items.join("&"), this.headers, this.complete);
        }
        else {
            this.form.setAttribute("action", url);
            this.form.setAttribute("method", method);
            this.form.submit();
        }
    };
    
    this.complete = function(request) {
        alert(request.responseText);
    };
    this.analyze();
});Class.load("Hrcbc.Validate");

Class.register("Hrcbc.Controls.Control", function(element, args, events) {
    this.id = Hrcbc.Guid.newGuid().toString("n");
    this.$ISCONTROL = true;
    this.element = element;
    this.$INITED = false;
    this.isDraging = false;
    this.dragInited = false;
    this.dragable = false;
    this.dragRect = null;
    this.dragControl = null;
    this.hitPoint = null;
    this.$MASKINITED = false;
    this.$CENTERINITED = false;
    this.$MASKFRAME = null;
    this.maskable = false;
    this.maskTimer = null;
	this.anchorTimer = null;
    this.enableSkin = true;
    this.childs = [];
    
    this.init = function(args) {
		this.$INITED = false;
        this.apply(args);
        if (this.skinHtml) this.setSkin();
        else if (this.skin) this.loadSkin();
        if (typeof (this.element) == "string") {
            if (Hrcbc.Validate.isHtml(this.element)) {
                var panel = document.createElement("div");
                panel.innerHTML = this.element;
                this.element = panel.firstChild;
                this.$ISNEWCREATED = true;
            }
            else {
                var o = document.getElementById(this.element);
                if (o) {
                    this.element = o;
                    this.parent = o.parentNode;
                }
            }
        }
        if (!this.element) {
            this.element = document.createElement(this.tag || "div");
            this.$ISNEWCREATED = true;
        }
		this.element.$CONTROL = this;
        this.$INITED = true;
        this.apply();
    };
    
    this.apply = function(args) {
        this.extend(args, true);
        if (this.$INITED) {            
            if (this.style)
                this.setStyle(this.style);
            if (this.cssClass)
                this.setCssClass(this.cssClass);
            if (this.alpha)
                this.setStyle("alpha", this.alpha);
            if (this.width)
                this.setStyle("width", String(this.width).toLowerCase() == "auto" ? "auto" : (String(parseInt(this.width)) + "px"));
            if (this.height)
                this.setStyle("height", String(this.height).toLowerCase() == "auto" ? "auto" : (String(parseInt(this.height)) + "px"));
            if (!Object.isNull(this.html))
                this.setHtml(this.html);
            if (this.maskable == true)
                this.mask(true);
            if (this.anchorOptions && this.anchorOptions.enable == true)
                this.anchor();
            if (this.dragable == true)
                this.drag(true, this.element, this.dragRect);
			if (this.visible == false) this.hide();
            else this.show();
        }
    };
    
    this.isInit = function() {
		if (this.$ISNEWCREATED) {
            var where;
            if (!this.parent) {
                if (!Hrcbc.$ISLOAD) {
                    this.$TEMPID = "tmp_" + Hrcbc.Guid.newGuid().toString("n");
                    document.write("<div id=\"" + this.$TEMPID + "\"></div>");
                    var p = document.getElementById(this.$TEMPID);
                    if (p) this.parent = p.parentNode;
                    else Hrcbc.onload(this.show.delegate(this));
                }
                else {
                    if (this.$TEMPID) {
                        this.parent = this.$TEMPPARENT = new Hrcbc.Controls.Control(this.$TEMPID);
                        where = "afterend";
                    }
                    else
                        this.parent = document.body || document.documentElement;
                }
            }
            if (this.parent) {
                if (typeof (this.parent) == "string")
                    this.parent = document.getElementById(this.parent);
                this.parent.appendChild(this.element, where);
                this.$ISNEWCREATED = false;
            }
        }
        if (this.$INITED == true && !Object.isNull(this.element) && typeof (this.element) == "object")
            return true;
        return false;
    };
    
    this.show = function() {
        if (!this.isInit()) return;        
        if (this.element.style["visibility"].toLower() == "hidden")
            this.setStyle("visibility", "visible");
        this.setStyle("display", "");
        if (this.$TEMPID && !this.$ISNEWCREATED) {
            if (this.$TEMPPARENT) {
                this.$TEMPPARENT.destory();
                delete this.$TEMPPARENT;
            }
            else {
                var o = document.getElementById(this.$TEMPID);
                if (o) o.parentNode.removeChild(o);
            }
            delete this.$TEMPID;
        }
    };
    
    this.position = function(absolute) {
        if (!this.isInit()) return {x:0,y:0};
        if (absolute) return Hrcbc.getAbsolutePosition(this.element);
        else return Hrcbc.getRelativePosition(this.element);
    };
    
    this.setHtml = function(html, override) {
        if (!this.isInit()) return;
        if (override == false) this.element.innerHTML += html;
        else this.element.innerHTML = html;
        this.$CONTROLS = null;
        this.show();
    };
    
    this.appendChild = function(child, where) {
        if (!child) return;
        if (child.$ISCONTROL && child.element) {
            var o = this.insertHtml(child.element, where);
            child.parent = this;
            child.$ISNEWCREATED = false;
            return o;
        }
        return this.insertHtml(child, where);
    };
    
    this.addChild = function(child, index) {
        if (!child || typeof (child) != "object") return;
        if (index == null || index == undefined || index >= this.element.childNodes.length || index < 0)
            return this.appendChild(child);
        var nextSibling = this.element.childNodes[index];
        if (child.$ISCONTROL && child.element) {
            var o = this.insertBefore(child.element, nextSibling);
            child.parent = this;
            child.$ISNEWCREATED = false;
            return o;
        }
        return this.insertBefore(child, nextSibling);
    };
    
    this.insertBefore = function(html, element) {
        this.insertHtml(html, "beforebegin", element);
    };
    
    this.insertAfter = function(html, element) {
        this.insertHtml(html, "afterend", element);
    };
    
    this.insertFirst = function(html, element) {
        this.insertHtml(html, "afterbegin", element);
    }
    
    this.insertHtml = function(html, where, element) {
        element = element || this.element;
        var isHtml = typeof (html) == "string";
        if (element.insertAdjacentHTML && element.insertAdjacentElement) {
            switch (where) {
                case "beforebegin":
                    isHtml ? element.insertAdjacentHTML('BeforeBegin', html) : element.insertAdjacentElement('BeforeBegin', html);
                    return element.previousSibling;
                case "afterbegin":
                    isHtml ? element.insertAdjacentHTML('AfterBegin', html) : element.insertAdjacentElement('AfterBegin', html);
                    return element.firstChild;
                default:
                case "beforeend":
                    isHtml ? element.insertAdjacentHTML('BeforeEnd', html) : element.insertAdjacentElement('BeforeEnd', html);
                    return element.lastChild;
                case "afterend":
                    isHtml ? element.insertAdjacentHTML('AfterEnd', html) : element.insertAdjacentElement('AfterEnd', html);
                    return element.nextSibling;
            }
        }
        var range = element.ownerDocument.createRange();
        var frag;
        switch (where) {
            case "beforebegin":
                if (isHtml) {
                    range.setStartBefore(element);
                    frag = range.createContextualFragment(html);
                }
                element.parentNode.insertBefore(frag || html, element);
                return element.previousSibling;
            case "afterbegin":
                if (element.firstChild) {
                    if (isHtml) {
                        range.setStartBefore(element.firstChild);
                        frag = range.createContextualFragment(html);
                    }
                    element.insertBefore(frag || html, element.firstChild);

                    return element.firstChild;
                } else {
                    isHtml ? (element.innerHTML = html) : element.appendChild(html);
                    return element.firstChild;
                }
            default:
            case "beforeend":
                if (element.lastChild) {
                    if (isHtml) {
                        range.setStartAfter(element.lastChild);
                        frag = range.createContextualFragment(html);
                    }
                    element.appendChild(frag || html);
                    return element.lastChild;
                } else {
                    isHtml ? (element.innerHTML = html) : element.appendChild(html);
                    return element.lastChild;
                }
            case "afterend":
                if (isHtml) {
                    range.setStartAfter(element);
                    frag = range.createContextualFragment(html);
                }
                element.parentNode.insertBefore(frag || html, element.nextSibling);
                return element.nextSibling;
        }
        return null;
    };
    
    this.setPosition = function(x, y) {
        if (!this.isInit()) return;
        this.setStyle("left", String(x) + "px");
        this.setStyle("top", String(y) + "px");
    };
    
    this.hide = function(visibleMode) {
		if (!this.isInit()) return;
        if (!Object.isNull(visibleMode))
            this.visibleMode = visibleMode;
        if (this.visibleMode) {
            this.setStyle("visibility", "hidden");
            this.setStyle("display", "");
        }
        else {
            this.setStyle("display", "none");
        }
    };
    
    this.setStyle = function(name, value) {
        if (!this.isInit()) return;
        if (Object.isNull(name)) return;
        if (Object.isNull(value) && /.+[:]{1,1}.+/.test(name)) {
            if (!Object.isNull(this.element.style.cssText))
                this.element.style.cssText = name;
            else
                this.setAttribute("style", name);
            return;
        }
        while (name.indexOf("-") >= 0) {
            var index = name.indexOf("-");
            name = name.substring(0, index) + name.charAt(index + 1).toUpperCase() + name.substring(index + 2, name.length);
        }
        if (/float$/i.test(name)) {
            this.element.style["cssFloat"] = value;
            this.element.style["styleFloat"] = value;
        }
        else if (/(^alpha$)|(opacity$)/i.test(name) || (/^filter$/i.test(name) && /opacity/i.test(value))) {
            this.element.style["filter"] = "alpha(opacity={0});".format(value);
            this.element.style["MozOpacity"] = value * 0.01;
            this.element.style["opacity"] = value * 0.01;
            this.alpha = value;
        }
        else {
            if (/^width|height$/ig.test(name) && value.toLowerCase() != "auto" && parseInt(value) < 0) return;
            this.element.style[name] = value;
        }
        if (this.$MASKINITED && /^width|height|right|bottom|left|top|display|visibility$/i.test(name)) {
            if (/^width|height$/.test(name)) {
                if (this.maskOptions.fullscreen) {
                    this.$MASK.setStyle(name, value);
                    if (this.$MASKFRAME != null && /^width|height$/.test(name))
                        this.$MASKFRAME.setStyle(name, value);
                }
            }
            else this.$MASK.setStyle(name, value);
        }
    };
    
    this.setCssClass = function(className) {
		if (!this.isInit()) return;
        if (!className) return;
        if (className.charAt(0) == ".")
            className = className.substring(1, className.length);
        if (Hrcbc.Browser.isIE())
            this.setAttribute("className", className);
        else
            this.setAttribute("class", className);
    };
    
    this.getCssClass = function() {
        var className = this.getAttribute("className");
        if (!className) className = this.getAttribute("class");
        return className || "";
    };
    
    this.addCssClass = function(className) {
        if (className.charAt(0) == ".")
            className = className.substring(1, className.length);
        var classes = this.getCssClass().split(" ").removeEmpty();
        if (!classes.contains(className)) classes.push(className);
        this.setCssClass(classes.join(" "));
    };
    
    this.removeCssClass = function(className) {
        if (className.charAt(0) == ".")
            className = className.substring(1, className.length);
        var classes = this.getCssClass().split(" ").removeEmpty();
        var index = classes.indexOf(className);
        if (index == -1) return;
        classes.splice(index, 1);
        this.setCssClass(classes.join(" "));
    };
    
    this.addStyle = function(ruleName, cssText, index) {
        if (!this.isInit()) return;
        Hrcbc.addStyle(ruleName, cssText, index);
        var match = ruleName.match(/(\.\w+)/g);
        if (Object.isNull(match)) return;
        this.addCssClass(match.last());
    };
    
    this.loadStyle = function(styleUrl) {
        Hrcbc.loadStyle(styleUrl);
    };
    
    this.size = function() {
        var o = this.element;
        if (arguments.length > 0) o = arguments[0];
        if (!o || typeof (o) != "object") return {width:0,height:0};
        o = o.element || o;
        return Hrcbc.getElementSize(o);
    };
    
    this.setSize = function(width, height) {
        this.setStyle("width", String(width) + "px");
        this.setStyle("height", String(height) + "px");
    }
    
    this.setAttribute = function(name, value) {
        if (!this.isInit()) return;
        this.element.setAttribute(name, value);
    };
    
    this.getAttribute = function(name) {
        if (!this.isInit()) return "";
        return this.element.getAttribute(name) || this.element[name];
    };
    
    this.setSkin = function(skinHtml) {
		if (!this.isInit()) return;
        if (!this.enableSkin) return;
        if (this.skinOptions.loadStyle != false) {
            this.loadStyle("{0}/resources/{1}/{2}.css".format(Hrcbc.path(), this.theme || "default", this.skin));
            this.loadStyle("{0}/resources/{1}/common.css".format(Hrcbc.path(), this.theme || "default"));
        }
        this.skinHtml = skinHtml || this.skinHtml;
        if (!this.skinHtml) return;
        this.skinHtml = this.skinHtml.replace(/{path}/ig, Hrcbc.path());
        this.element = this.skinHtml;
        this.$CONTROLS = null;
    };
    
    this.loadSkin = function(skin, options) {
        if (!this.enableSkin) return;
        this.skinOptions = options || this.skinOptions || {};
        this.skin = skin || this.skin;
        if (!this.skin) return;
        var skinName = "{0}_{1}".format(this.theme || "default", this.skin);
        var commonName = "{0}_common".format(this.theme || "default");
        if (Object.isNull(Hrcbc.Controls.$SKINS)) Hrcbc.Controls.$SKINS = {};
        var skinText = Hrcbc.Controls.$SKINS[skinName];
        if (!skinText && this.skinOptions.loadHtml != false) {
            var skinUrl = this.skin.startsWith("http://") ? this.skin : ("{0}/resources/{1}/{2}.html".format(Hrcbc.path(), this.theme || "default", this.skin));
            skinText = Hrcbc.AjaxRequest.getText(skinUrl);
            Hrcbc.Controls.$SKINS[skinName] = skinText;
        }
        this.setSkin(skinText);
    };
    
    this.moveTop = function() {
        this.setStyle("z-index", Hrcbc.getMaxZOrder());
    };
    
    this.drag = function(enable, control, rect) {
		if (!this.isInit()) return;
        if (enable == true) {
            this.dragable = true;
            if (!this.dragInited && this.isInit()) {
                control = control || this.dragControl;
                if (control && typeof (control) == "string")
                    control = document.getElementById("id");
                if (!control || typeof (control) != "object")
                    control = this;
                else if (!control.element) control = new Hrcbc.Controls.Control(control);
                this.dragControl = control;
                this.dragRect = rect;
                this.setStyle("position", "absolute");
                Hrcbc.Event.addEventListener(this.dragControl.element, "mousedown", this.startDrag.delegate(this));
                Hrcbc.Event.addEventListener(document, "mousemove", this.draging.delegate(this));
                Hrcbc.Event.addEventListener(document, "mouseup", this.endDrag.delegate(this));
            }
            this.dragControl.addCssClass("dragable");
            return;
        }
        if (this.dragControl) this.dragControl.removeCssClass("dragable");
        this.dragable = false;
    };
    
    this.startDrag = function() {
        if (this.dragable) {
            this.moveTop();
            Hrcbc.selectable(false);
            this.isDraging = true;
            var thisPos = this.position(true);
            var eventPos = Hrcbc.Event.position();
            this.hitPoint = {x : eventPos.x - thisPos.x, y :  eventPos.y - thisPos.y};

        }
    };
    
    this.draging = function() {
        if (!this.dragable || !this.isDraging) return;
        var position = Hrcbc.Event.position();
        position.x = position.x - this.hitPoint.x;
        position.y = position.y - this.hitPoint.y;
        if (this.dragRect) {
            var scrollPoint = Hrcbc.getScrollPosition();
            var size = this.size();
            if (position.x < this.dragRect.x + scrollPoint.x) position.x = this.dragRect.x + scrollPoint.x;
            if (position.x + size.width > this.dragRect.x + this.dragRect.width + scrollPoint.x) position.x = this.dragRect.x + this.dragRect.width - size.width + scrollPoint.x;
            if (position.y < this.dragRect.y + scrollPoint.y) position.y = this.dragRect.y + scrollPoint.y;
            if (position.y + size.height > this.dragRect.y + this.dragRect.height + scrollPoint.y) position.y = this.dragRect.y + this.dragRect.height - size.height + scrollPoint.y;
        }
        this.setPosition(position.x, position.y);
    };
    
    this.endDrag = function() {
        this.isDraging = false;
        Hrcbc.selectable(true);
    };
    this.fade = function() {
    };
    
    this.mask = function(enable, options) {
		if (!this.isInit()) return;
        this.maskOptions = options || this.maskOptions || {};
        this.maskable = enable ? true : false;
        if (this.maskable) {
            if (this.$MASKINITED != true) {
                this.$MASK = new Hrcbc.Controls.Control(null, {
                    parent: this,
                    style: "position:absolute"
                });
                this.parent.insertBefore(this.$MASK.element, this.element);
                this.$MASK.parent = this.parent;
                if (Hrcbc.Browser.isIE() && Hrcbc.Browser.getVersion() < 7) {
                    this.$MASK.setHtml("<iframe style=\"Z-INDEX: -1; FILTER: progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);LEFT: 0px; POSITION: absolute; TOP: 0px;\" src=\"about:blank\"></iframe>");
                    this.$MASKFRAME = this.$MASK.selectSingleNode("//iframe");
                    this.$MASKFRAME.show();
                }
            }
            var setMask = function() {
                if (!this.maskable) return;
                var thisSize = this.size();
                var docSize = Hrcbc.getVisibleDocumentSize();
                if (this.maskOptions.fullscreen) {
                    this.$MASK.setSize(docSize.width, docSize.height);
                    if (this.$MASKFRAME)
                        this.$MASKFRAME.setSize(docSize.width, docSize.height);
                    this.$MASK.anchor();
                }
                else {
                    this.$MASK.setSize(thisSize.width, thisSize.height);
                    if (this.$MASKFRAME)
                        this.$MASKFRAME.setSize(thisSize.width, thisSize.height);
                }
                this.$MASK.setStyle("background-color", this.maskOptions.bgcolor || "#787878");
                this.$MASK.setStyle("alpha", Object.isNull(this.maskOptions.alpha) ? 30 : this.maskOptions.alpha);               
            } .delegate(this);
			this.$MASKINITED = true;
						this.maskTimer = window.setInterval(setMask,200);
        }
        this.maskable ? this.$MASK.show() : this.$MASK.hide();
    };
    this.checkAnchorOptions = function() {
        if (!this.anchorOptions || !this.anchorOptions.enable) return;
        if (!this.anchorOptions) this.anchorOptions = {};
        if (!this.anchorOptions.horizontal) this.anchorOptions.horizontal = "center";
        if (!this.anchorOptions.vertical) this.anchorOptions.vertical = "center";
        if (!this.anchorOptions.offsetX) this.anchorOptions.offsetX = 0;
        if (!this.anchorOptions.offsetY) this.anchorOptions.offsetY = 0;
    };
    
    this.anchor = function(options) {
		if (!this.isInit()) return;
        this.anchorOptions = options || this.anchorOptions || { enable: true, horizontal: "center", vertical: "center", offsetX: 0, offsetY: 0 };
        this.checkAnchorOptions();       
        var ruleName = ".control_{0}_{1}_{2}".format(this.anchorOptions.horizontal, this.anchorOptions.vertical, this.id);		
        if (this.anchorOptions.enable) {			
			var cssText = "";
			if (Hrcbc.Browser.isIE() && !Hrcbc.Browser.isIE7()) {
				cssText += "position:absolute;/*IE6*/\r\n";
				if (this.anchorOptions.horizontal == "center") 
					cssText += "_left:expression(eval(document.compatMode && document.compatMode=='CSS1Compat') ? documentElement.scrollLeft + (document.documentElement.clientWidth-this.offsetWidth)/2 : document.body.scrollLeft + (document.body.clientWidth - this.clientWidth)/2);/*IE5 IE5.5*/\r\n";
				if (this.anchorOptions.vertical == "center") 
					cssText += "_top: expression(eval(document.compatMode && document.compatMode=='CSS1Compat') ? documentElement.scrollTop  + (document.documentElement.clientHeight-this.offsetHeight)/2 : document.body.scrollTop + (document.body.clientHeight - this.clientHeight)/2);/*IE5 IE5.5*/\r\n";
				if (this.anchorOptions.horizontal == "right") 
					cssText += "_left:expression(eval(document.compatMode && document.compatMode=='CSS1Compat') ? documentElement.scrollLeft - ({$offsetX$}) + (document.documentElement.clientWidth-this.offsetWidth) :  document.body.scrollLeft - ({$offsetX$}) + (document.body.clientWidth - this.clientWidth));/*IE5 IE5.5*/\r\n";
				if (this.anchorOptions.vertical == "bottom") 
					cssText += "_top: expression(eval(document.compatMode && document.compatMode=='CSS1Compat') ? documentElement.scrollTop + (document.documentElement.clientHeight-this.offsetHeight) - ({$offsetY$}) : document.body.scrollTop - ({$offsetY$}) + (document.body.clientHeight - this.clientHeight));/*IE5 IE5.5*/\r\n";
				if (this.anchorOptions.horizontal == "left") 
					cssText += "_left:expression(documentElement.scrollLeft + ({$offsetX$}));/*IE5 IE5.5*/\r\n";
				if (this.anchorOptions.vertical == "top") 
					cssText += "_top: expression( documentElement.scrollTop + ({$offsetY$}));/*IE5 IE5.5*/\r\n";
			}
			else {
				cssText = "{$offsetHorizontal$}:{$offsetLeft$}!important;/*FF IE7*/\r\n";
				cssText += "{$offsetVertical$}:{$offsetTop$}!important;/*FF IE7*/\r\n";
				if (this.anchorOptions.horizontal == "center") {
					cssText += "margin-left:-{$marginLeft$}px!important;/*FF IE7 该值为本身宽的一半 */\r\n";
					cssText += "margin-left:0px;\r\n";
				}
				if (this.anchorOptions.vertical == "center") {
					cssText += "margin-top:-{$marginTop$}px!important;/*FF IE7 该值为本身高的一半*/\r\n";
					cssText += "margin-top:0px;\r\n";
				}
				cssText += "position:fixed!important;/*FF IE7*/\r\n";
			}
			var thisSize = this.size();
			cssText = cssText.replace(/\{\$marginLeft\$\}/ig, thisSize.width / 2);
			cssText = cssText.replace(/\{\$marginTop\$\}/ig, thisSize.height / 2);
			cssText = cssText.replace(/\{\$offsetHorizontal\$\}/ig, this.anchorOptions.horizontal == "right" ? "right" : "left");
			cssText = cssText.replace(/\{\$offsetVertical\$\}/ig, this.anchorOptions.vertical == "bottom" ? "bottom" : "top");
			cssText = cssText.replace(/\{\$offsetX\$\}/ig, this.anchorOptions.offsetX);
			cssText = cssText.replace(/\{\$offsetY\$\}/ig, this.anchorOptions.offsetY);
			cssText = cssText.replace(/\{\$offsetLeft\$\}/ig, this.anchorOptions.horizontal == "center" ? "50%" : (this.anchorOptions.offsetX + "px"));
			cssText = cssText.replace(/\{\$offsetTop\$\}/ig, this.anchorOptions.vertical == "center" ? "50%" : (this.anchorOptions.offsetX + "px"));
			this.addStyle(ruleName, cssText);
        }else this.removeCssClass(ruleName);
    };
    
    this.selectNodes = function(path, count) {
        var elements = Hrcbc.selectNodes(this.element, path, count);
        var nodes = [];
        for (var i = 0; i < elements.length; i++) {
            nodes.push(new Hrcbc.Controls.Control(elements[i]));
        }
        return nodes;
    };
    
    this.selectSingleNode = function(path) {
        var nodes = this.selectNodes(path, 1);
        if (nodes.length > 0)
            return nodes[0];
        return null;
    };
    
    this.findControl = function(path) {
        if (!this.$CONTROLS) this.$CONTROLS = {};
        else if (this.$CONTROLS[path]) return this.$CONTROLS[path];
        var control = this.selectSingleNode(path);
        if (control == null) return null;
        if (!this.$CONTROLS[path]) this.$CONTROLS[path] = control;
        return control;
    };
    
    this.findControls = function(path) {
        if (!this.$CONTROLS) this.$CONTROLS = {};
        var controls = this.selectNodes(path);
        if (controls.length > 0) {
            this.$CONTROLS[path] = controls;
            return controls;
        }
        return [];
    };
    
    this.contains = function(o) {
        if (o == this.element) return true;
        return Hrcbc.isContains(this.element, o);
    };
    
    this.destory = function() {
        Hrcbc.Event.removeEventListener(this.element);
        Hrcbc.Event.removeEventListener(this);
        this.element.parentNode.removeChild(this.element);
        if (this.maskTimer) window.clearInterval(this.maskTimer);
    };
    this.init(args);
    if (events && typeof (events) == "object") {
        for (var e in events) {
            if (!Object.isOriginal(e))
                Hrcbc.Event.addEventListener(this, e, events[e]);
        }
    }
});
Class.load("Hrcbc.Controls.Window");
Class.register("Hrcbc.Controls.DialogBox", function(args) {
    this.base = Hrcbc.Controls.Window;
    this.base(args);

});
Class.load("Hrcbc.Controls.Control");


Class.register("Hrcbc.Controls.FileUploader",function(object,args){
	this.base = Hrcbc.Controls.Control;
	this.base(object,args);
	this.isAjaxUpload = this.isAjaxUpload || true; 	this.autoPosition = this.autoPosition || true; 	this.positionTimer = null;
	this.progressTimer = null;
	this.uploadButtonCssClass = this.uploadButtonCssClass || ""; 	this.uploadInputCssClass = this.uploadButtonCssClass || "";	
	this.value = "";		this.name = this.name || Hrcbc.Guid.newGuid().toString("n");	
	this.enableSubmit = true;
	
	this.init = this.init.callback(function(){
		this.form = this.element.form;
		if(this.isAjaxUpload || !this.form) {
			this.form = document.createElement("form");
			document.body.appendChild(this.form);				
		}		
        if(this.form.encoding && !Hrcbc.Browser.isSafari()) this.form.setAttribute('encoding','multipart/form-data');
        else this.form.setAttribute("enctype","multipart/form-data");
		this.form.setAttribute("method","post");
		this.form.setAttribute("target","frame{0}".format(this.id));
		this.form.onsubmit = function() {
			this.submit();
			return false;
		}.delegate(this);
		this.panel = new Hrcbc.Controls.Control(null,{parent:this.form,alpha:0});
		this.panel.setHtml("<div cname=\"uploadPanel\" style=\"position:absolute\"><input type=\"text\" cname=\"uploadInput\" clsss=\"{0}\" /><input type=\"button\" value=\"浏览...\" clsss=\"{1}\" cname=\"uploadButton\" /></div><div style=\"position:absolute;\"><input id=\"{3}\" name=\"{3}\" cname=\"fileInput\" type=\"file\" /></div><iframe style=\"width:1px;height:1px;border:0px;\" id=\"frame{2}\" name=\"frame{2}\"></iframe>".format(this.uploadInputCssClass,this.uploadButtonCssClass,this.id,this.name));
		this.uploadInput = 	this.panel.findControl("//*[@cname=uploadInput]");
		this.uploadButton = this.panel.findControl("//*[@cname=uploadButton]");
		this.fileInput = this.panel.findControl("//*[@cname=fileInput]");
		this.fileInput.setStyle("alpha",0);
		this.fileInput.addEventListener("change",this.fileInputChange.delegate(this),this.fileInput.element);
		this.resize();
		this.resetPosition();
		if (this.autoPosition) {
			if (this.positionTimer) 
				window.clearInterval(this.positionTimer);
			this.positionTimer = window.setInterval(this.resetPosition.delegate(this), 1000);
		}
	},null,this);
	
	this.resize = function() {
		this.panel.element.childNodes[1].style.width = String(this.uploadInput.size().width + this.uploadButton.size().width ) + "px";
		this.fileInput.setStyle("float","right");
				this.panel.element.childNodes[0].style.width = String(parseInt(this.panel.element.childNodes[1].style.width)+ (Hrcbc.Browser.isSafari() ? 10 : 0)) + "px";
	};
	
	this.resetPosition = function() {
		var pos = this.position(true);
		this.hide(true);
		this.panel.setStyle("position","absolute");
		this.panel.setPosition(pos.x,pos.y + (Hrcbc.Browser.isIE() ? -2 : 0));
	};
	
	this.fileInputChange = function() {		
		this.uploadInput.element.value = this.fileInput.element.value;
		this.value = this.fileInput.element.value;
		this.status = null;
		if(this.progress) {
			this.progress.setValue(0);
			this.progress.hide();
		};
		if(this.change) this.change.apply(this,[this.value]);
		if(this.autoSubmit != false) this.submit();
	};
	
	this.submit = function( action, progressUrl,callback){
		if(!this.enableSubmit) return;
		this.action = action || this.action;
		this.action = this.action.replace(/(RequestId=\w*&?)/i,"");
		this.action = this.action.replace(/IsAjaxUpload=\w*&?/i,"");				
		this.action = this.action + (this.action.indexOf("?")>0  ? "&":"?") + "RequestId={0}&IsAjaxUpload={1}".format(this.id,this.isAjaxUpload);
		this.progressUrl = progressUrl || this.progressUrl;
		this.progressUrl = this.progressUrl.replace(/(RequestId=\w*&?)/i,"");
		this.progressUrl = this.progressUrl + (this.progressUrl.indexOf("?")>0?"&":"?") + "RequestId={0}".format(this.id);
		this.form.setAttribute("action",this.action);
		if (!this.progress && this.progressUrl) {
			Class.load("Hrcbc.Controls.Progress");
			this.progress = new Hrcbc.Controls.Progress();
		}  
		if(this.progress && this.progressUrl && !this.progressTimer) {		 
			var _this = this;
			this.status = "uploading";
			this.progressTimer = window.setInterval(function(){
			    if(_this.request != null) {
			        _this.request.abort();
			        _this.request = null;
			    }
				_this.request = Hrcbc.AjaxRequest.getText(_this.progressUrl,true,function(){
					var p = _this.request.responseText.parseJSON();
					if(p) {
						_this.data = p;
					    _this.progress.setValue(p.Progress);
					    if(p.IsComplete) {
					        _this.status = "complete";
					        window.clearInterval(_this.progressTimer);
							_this.progressTimer = null;
					        _this.request.abort();
			                _this.request = null;
							if (!Hrcbc.Browser.isFirefox()) {
								var frame = document.getElementById("frame{0}".format(_this.id));
								frame.contentWindow.document.write("complete");
								frame.contentWindow.document.close();
							}
			                _this.progress.hide();
			                if(_this.progress.complete) 
			                    _this.progress.complete.apply(_this,p);
							if(_this.complete) _this.complete(p);
							if(callback) callback();							
					    }
					}
				});
			},1000);
		} 		
		this.form.submit();
	}
	this.init();
});
    


Class.register("Hrcbc.Controls.ObjectControl", function(args) {
    this.$INITED = false;
    this.$CREATED = false;
    this.parameters = {};     this.attributes = {};     this.embedAttributes = {};
    
    this.init = function(args) {
        this.destory();
        if (args && typeof (args) == "object") this.extend(args, true);
        if (!this.id)
            this.id = "O" + Hrcbc.Guid.newGuid().toString("n");
        this.setAttribute("id", this.id);
        this.setAttribute("name", this.id);
        this.$CREATED = false;
        this.$INITED = true;
    };
    
    this.isInit = function() {
        if (this.$INITED == true && !Object.isNull(this.element) && typeof (this.element) == "object")
            return true;
        return false;
    };
    
    this.show = function() {
        if (!this.$CREATED) {
            this.element = '';
            if (Hrcbc.Browser.isIE()) {
                this.element += '<object ';
                for (var a in this.attributes) {
                    if (!Object.isOriginal(a))
                        this.element += ' {0}="{1}" '.format(a, this.attributes[a]);
                }
                this.element += ">";
                for (var p in this.parameters) {
                    if (!Object.isOriginal(p))
                        this.element += '<param name="{0}" value="{1}" />'.format(p, this.parameters[p]);
                }
                this.element += '</object>';
            }
            else {
                this.element += '<embed ';
                for (var a in this.embedAttributes) {
                    if (!Object.isOriginal(a))
                        this.element += ' {0}="{1}" '.format(a, this.embedAttributes[a]);
                }
                this.element += '> </embed>';
            }
            if (!this.parent && !Hrcbc.$ISLOAD) {
                document.write(this.element);
            }
            else {
                this.parent = this.parent || document.body || document.documentElement;
                if (typeof (this.parent) == "string")
                    this.parent = document.getElementById(this.parent);
                this.parent.innerHTML += this.element;
            }
            this.getElement();
            this.$CREATED = true;
        }
        if (this.isInit() && this.element.style) {
            this.element.style["display"] = "";
            this.element.style["visibility"] = "visible";
        }
    }
    
    this.hide = function(visibleMode) {
        if (this.isInit() && this.element.style) {
            if (visibleMode) {
                this.element.style["visibility"] = "hidden";
                this.element.style["display"] = "";
            }
            else {
                this.element.style["display"] = "none";
            }
        }
    };
    
    this.getElement = function() {
        this.element = Hrcbc.getObject(this.id);
		return this.element;
    };
	
    this.call = function() {
        if (this.getElement()) {
            var args = Array.parse(arguments);
            var method = args.shift();
            var command = "Hrcbc.getObject('{0}').{1}({2});".format(this.id,method,args.length > 0 ? ('"{0}"'.format(args.join('","'))):'');
			try {
				return eval(command);
			}
			catch(e) {}
        }
    };
    
    this.setAttribute = function(name, value) {
        if (typeof (name) == "object") {
            for (var i in name) {
                if (!Object.isOriginal(i))
                    this.setAttribute(i, name[i]);
            }
        }
        if (/^(classid|onafterupdate|onbeforeupdate|onblur|oncellchange|onclick|ondblclick|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondrop|onfinish|onfocus|onhelp|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup|onload|onlosecapture|onpropertychange|onreadystatechange|onrowsdelete|onrowenter|onrowexit|onrowsinserted|onstart|onscroll|onbeforeeditfocus|onactivate|onbeforedeactivate|ondeactivate|type|codebase|id)$/.test(name))
            this.attributes[name] = value;
        else if (/^(width|height|align|vspace|hspace|class|title|accesskey|name|tabindex)$/.test(name))
            this.attributes[name] = this.embedAttributes[name] = value;
        else
            this.parameters[name] = this.embedAttributes[name] = value;
    };
    
    this.getAttribute = function(name) {
        if (Hrcbc.Browser.isIE())
            return this.attributes[name] || this.parameters[name];
        else
            return this.embedAttributes[name];
    };
    
    this.destory = function() {
        this.getElement();
        if (this.element)
            this.element.parentNode.removeChild(this.element);
    };
    this.init(args);
});
Class.load("Hrcbc.Controls.ObjectControl");

Class.register("Hrcbc.Controls.FlashPlayer", function(args, attributes, variables) {
    this.base = Hrcbc.Controls.ObjectControl;
    this.base(args);
    this.setAttribute((attributes || {}).extend({
        classid: 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',
        type: "application/x-shockwave-flash",
        codebase: 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
        pluginspage: 'http://www.adobe.com/go/getflashplayer',
        quality: 'best',
        align: 'middle',
        play: 'true',
        loop: 'true',
        scale: 'noscale',
        wmode: 'window',
        devicefont: 'true',
        menu: 'false',
        allowFullScreen: 'false',
        allowScriptAccess: 'always',
        salign: '',
        src: attributes ? (attributes.src || attributes.movie) : '',
        movie: attributes ? (attributes.src || attributes.movie) : '',
        width: 550,
        height: 400
    }, false));
    if (variables && typeof (variables)) {
        var vars = [];
        for (var i in variables) {
            if (!Object.isOriginal(i))
                vars.push("{0}={1}".format(i, variables[i]));
        }
        this.setAttribute("FlashVars", vars.join("&"));
    }
});
Class.register("Hrcbc.Controls.MenuItem", function(args) {
    this.base = Hrcbc.Controls.Control;
    this.base(null, (args || {}).extend({
        tag: 'li',
        ownerMenu: null, 	        childMenu: null, 	        direction: null, 	        text: '', 			        href: null, 		        target: null, 		        selected: false, 	        cssClass: 'menu_item',
        delay: 100,
        selectedStyle: null, 	        selectedCssClass: 'menu_item_selected'	    }, false));

    
    this.setText = function(text, href, target) {
        this.text = text || this.text;
        this.href = href || this.href;
        this.target = target || this.target || "_self";
        this.setHtml(this.href ? '<a href="{0}" target="{1}">{2}</a>'.format(this.href, this.target, this.text) : this.text);
    };
    
    this.setChildMenu = function(childMenu) {
        if (!childMenu || !(childMenu instanceof Hrcbc.Controls.Menu)) {
            childMenu = new Hrcbc.Controls.Menu(childMenu);
        }
        childMenu.parentMenu = this.ownerMenu;
        childMenu.root = this.ownerMenu.root;
        childMenu.parentObject = this;
        childMenu.extend({
            itemStyle: this.style,
            itemSelectedStyle: this.selectedStyle,
            itemCssClass: this.cssClass,
            itemSelectedCssClass: this.selectedCssClass,
            direction: this.direction            
        }, false, true);
        this.childMenu = childMenu;
        return this.childMenu;
    };
    
    this.setStatus = function(selected) {
        this.selected = selected;
        this.setStyle(this.selected ? (this.selectedStyle || this.style) : this.style);
        if (this.selectedCssClass) {
            if (this.selected) this.addCssClass(this.selectedCssClass);
            else this.removeCssClass(this.selectedCssClass);
        }
    };
    Hrcbc.Event.addEventListener(this.element, "click", function() {
        if (this.click) this.click(this);
    } .delegate(this));
    Hrcbc.Event.addEventListener(this.element, "mouseover", function() {        
        window.clearTimeout(this.timer);
        window.clearTimeout(this.ownerMenu.timer);
		if(this.ownerMenu.selectedItem) {
			if (this.ownerMenu.selectedItem.childMenu) {
				window.clearTimeout(this.ownerMenu.selectedItem.childMenu.timer);
				this.ownerMenu.selectedItem.childMenu.hide(true);
			}
			this.ownerMenu.selectedItem.setStatus(false);
			this.ownerMenu.selectedItem = null;
			this.ownerMenu.selectedIndex = -1;
		}
		this.setStatus(true);
        if (this.childMenu) {
			window.clearTimeout(this.childMenu.timer);			
            var pos = this.position(true);
            var size = this.size();
            var menuSize = this.ownerMenu.size();
            var menuPos = this.ownerMenu.position();
            var childSize = this.childMenu.size();
            var direction = this.direction;
            var left = pos.x;
            var top = pos.y;
            switch (direction) {
                case "left":
                    left -= childSize.width;
                    break;
                default:
                case "right":
                    left = menuPos.x + menuSize.width + 15;
                    break;
                case "top":
                    top -= childSize.height;
                    break;
                case "bottom":
                    top += size.height;
                    break;
            }
            this.childMenu.setStyle("position", "absolute");
            this.childMenu.setPosition(left, top);
            this.childMenu.show();
        }
        if (this.select) this.select(this);
    } .delegate(this));
    Hrcbc.Event.addEventListener(this.element, "mouseout", function() {
        if (this.childMenu) {
            var event = Hrcbc.Event.getEvent();
            window.clearTimeout(this.timer);
            this.timer = window.setTimeout(function() {
                                if (!this.childMenu.contains(event.relatedTarget)) {
                    this.setStatus(false);
                    this.childMenu.hide(true);
                    if (this.select) this.select(this, event);
                }
            } .delegate(this), this.delay);
        }
        else {
            this.setStatus(false);
        }
    } .delegate(this));
    Hrcbc.Event.addDispatcher(this);
    this.setText();
});
Class.load("Hrcbc.Controls.Control");
Class.load("Hrcbc.Controls.MenuItem");
Class.load("Hrcbc.Validate");


Class.register("Hrcbc.Controls.Menu", function(args) {
    this.base = Hrcbc.Controls.Control;
    this.base(null, (args || {}).extend({
        skin: 'menu',
        skinOptions: {
            loadHtml: false
        },
        tag: 'ul',
        items: [], 			        parentMenu: null, 	        parentObject: null,
        root: null, 		        selectedIndex: -1, 	        selectedItem: null,         itemStyle: null,               itemSelectedStyle: null,         itemCssClass: null,         itemSelectedCssClass: null,         direction: null,
		cssClass : "control_menu",
        delay: 100
    }, false));
    if (!this.root) this.root = this;
    
    this.load = function(url) {
        var oThis = this;
        Hrcbc.AjaxRequest.getText(url, true, function(request) {
            var data;
            if (request.responeXML)
                data = Hrcbc.Xml.parseJSON(request.responeXML);
            else if (request.reponseText)
                data = request.reponseText.parseJSON();
            if (data) oThis.create(data);
        });
    };
    
    this.create = function(data) {
        if (!data) return;
        if (data.items && data.items instanceof Array) {
            for (var i = 0; i < data.items.length; i++) {
                var dataItem = data.items[i];
                var item = this.addItem({
                    text: dataItem.text,
                    href: dataItem.href,
                    target: dataItem.target
                });
                if (dataItem.menu) {
                    var menu = item.setChildMenu();
                    menu.create(dataItem.menu);
                }
            }
        }
    };
    
    this.addItem = function(item) {
        if (!this.items) this.items = [];
        if (!item || !(item instanceof Hrcbc.Controls.MenuItem))
            item = new Hrcbc.Controls.MenuItem(item);
        item.extend({
            style: this.itemStyle,
            selectedStyle: this.itemSelectedStyle,
            cssClass: this.itemCssClass,
            selectedCssClass: this.itemSelectedCssClass,
            direction: this.direction
        }, false, true);
        item.apply();
        item.ownerMenu = this;
        this.addChild(item);
        this.items.push(item);
        item.addEventListener("select", function() {
            var _item = arguments[0];
            var event = arguments[1];
            if (!_item) return;
            var index = this.items.indexOf(_item);
            if (index >= 0) {
                if (_item.selected) {
                    this.selectedIndex = index;
                    this.selectedItem = _item;
                }
                else if (_item == this.selectedItem) {
                    this.selectedIndex = -1;
                    this.selectedItem = null;
                }
                if (this.itemselect)
                    this.itemselect(this, event);
            }
        } .delegate(this));
        return item;
    };
    Hrcbc.Event.addEventListener(this.element, "mouseover", function() {
        if (this.parentObject && this.parentObject.timer)
            window.clearTimeout(this.parentObject.timer);
        if (this.parentMenu && this.parentMenu.timer)
            window.clearTimeout(this.parentMenu.timer);
        this.show();
    } .delegate(this));
    Hrcbc.Event.addEventListener(this.element, "mouseout", function() {
        var event = Hrcbc.Event.getEvent();
        if (this.parentMenu) {
			window.clearTimeout(this.timer);
			this.timer = window.setTimeout(function() {
			    trace("menutimer");
                if (!this.contains(event.relatedTarget) && !(this.selectedItem &&
			            this.selectedItem.childMenu && this.selectedItem.childMenu.contains(event.relatedTarget))) {
                    var menu = this;
                    while (menu.parentMenu != null) {
                        if (menu.parentMenu.selectedItem && !menu.parentMenu.selectedItem.contains(event.relatedTarget)) {
                            menu.parentMenu.selectedItem.setStatus(false);
                            menu.parentMenu.selectedIndex = -1;
                            menu.parentMenu.selectedItem = null;
                        }
                        if (menu.parentMenu.contains(event.relatedTarget)) {
                            break;
                        }
                        if (menu.parentMenu.parentMenu)
                            menu.parentMenu.hide(true);
                        menu = menu.parentMenu;
                    }
                    this.hide(true);
                }
            } .delegate(this), this.delay);
        }
    } .delegate(this));
    Hrcbc.Event.addDispatcher(this);
   	this.hide(true);
});
Hrcbc.Controls.Menu.extend({
    
    createMenu: function(data) {
        var menu = new Hrcbc.Controls.Menu();
        if (typeof (data) == "object")
            menu.create(data);
        else if (typeof (data) == "string")
            menu.load(data);
        return menu;
    }
});
Class.load("Hrcbc.Controls.Control");
Class.register("Hrcbc.Controls.Progress",function( object, args) {	
	this.base = Hrcbc.Controls.Control;
	this.base(object,args);
	this.minValue = this.minValue || 0;				this.maxValue = this.maxValue || 100;			this.value = this.value || this.minValue; 		this.timer = null;
	this.maskable = true;
	this.initHtml = false;	
	this.anchorOptions = this.anchorOptions || {enable:true,horizontal:"right",vertical:"top",offsetX:10,offsetY:10};
	this.maskOptions = {
	    fullscreen : true,
	    aplha : 80,
	    bgcolor : "#909090"
	}; 
	
	this.init = this.init.callback(function() {		
		this.getValue();
	},null,this);
	
	this.setValue = function( value) {
		if(value) this.value = parseFloat(value);
		if(this.value < this.minValue)	this.value = this.minValue;
		else if(this.value > this.maxValue)	this.value = this.maxValue;
		if(!this.initHtml); {
		    this.setHtml("<div style=\"border:1px solid #dbdce3;background-color:#ffffae;padding:3px 10px 3px 10px;color:#444444\"><span cname=\"progressText\"></span></div>".format(Hrcbc.path()));			
		    this.progressText = this.findControl("//*[@cname=progressText]");
		    this.initHtml = true;		    
		}
		this.setStyle("alpha",80);
		this.progressText.setHtml("正在上传{0}%".format(value));
	};
	
	this.getValue = function( url) {	
		return this.value;
	};
	this.init();
});
Class.load("Hrcbc.Controls.Control");

Class.register("Hrcbc.Controls.TableCell", function(args) {
    this.base = Hrcbc.Controls.Control;
    this.base(null, (args || {}).extend({
        tag: "td",
        table: null,         row: null, 	        column: null, 	        rowspan: 1,         colspan: 1
    }, false));
    this.setHtml("&nbsp;");
	
	this.apply = this.apply.callback(function(){
		if(this.rowspan) 
			this.setAttribute("rowSpan",this.rowspan);
		if(this.colspan)
			this.setAttribute("colSpan",this.colspan);
	},null,this);
});
Class.load("Hrcbc.Controls.Control");

Class.register("Hrcbc.Controls.TableRow",function(args){
	this.base = Hrcbc.Controls.Control;
	this.base(null,(args || {}).extend({
		tag : "tr",
		type : "normal",
		table : null		},false));	
	this.cells = [];
	
	this.addCell = function( cell, index) {
		index = (index != null && index != undefined && typeof(index) == "number") ? index : this.cells.length;
		this.addChild(cell,index);
		this.cells[index] = cell;
		return cell;
	};
	
	this.merge = function( cell, colspan) {
		var colIndex = row.cells.indexOf(cell);
		if(colIndex + colspan > this.table.columns.length)
			colspan = this.table.columns.length - colIndex;
		for(var n=0; n<colspan; n++) {
			var c =this.cell(colIndex + n); 
			if(!c || c == cell) continue;
			this.removeCell(colIndex + n); 
		}
	};
	
	this.removeCell = function( cell) {
		if(cell instanceof Hrcbc.Controls.TableCell) {
			var i= this.cells.indexOf(cell);
			if(i >=0) this.cells[i] = null;
			cell.destory();
			delete cell;
			return;			
		}
		if(typeof(cell) == "number") {
			var c = this.cells[cell];
			if(c) {
				this.cells[cell] = null;
				c.destory();
				delete c;				
			}
		}		
	};
	
	this.cell = function( c) {
		var column = this.table.column(c);
		for(var i=0; i<this.cells.length; i++) {
			if(this.cells[i] && this.cells[i].column == column)
				return this.cells[i];
		}
		var rowIndex = this.table.rows.indexOf(this);
		var colIndex = this.table.columns.indexOf(column);
		for(var i=0; i<rowIndex; i++) {
			for(var n=0; n<colIndex; n++) {
				var cell = this.table.rows[i].cell(n);
				if(cell != null && (cell.rowspan+i) >= rowIndex && (cell.colspan + n) >= colIndex) 
					return cell;
			}
		};
		return null;
	};
	
	this.show = this.show.callback(function(){
		if(this.table && this.table.columns && this.table.columns.length > 0) {
			for(var i=0; i<this.table.columns.length; i++) {
				var cell = this.cell(i);
				if(!cell) {
					cell = new Hrcbc.Controls.TableCell({
						table : this.table,
						column : this.table.columns[i],
						row : this,
						tag : (this.type == "header" ? "th" : "td")
					});
					this.addCell(cell,i);
					if(this.type == "header")
						cell.setHtml(this.table.columns[i].name);
				}
			};
		}		
	},null,this);
});
Class.load("Hrcbc.Controls.Control");
Class.load("Hrcbc.Controls.TableRow");
Class.load("Hrcbc.Controls.TableCell");

Class.register("Hrcbc.Controls.Table", function(args) {
    this.base = Hrcbc.Controls.Control;
    this.base(null, (args || {}).extend({
        tag: "table",
        columns: [],
        cellspacing: 1,
        cellpadding: 1,
        border: 0
    }, false));
    this.rows = [];
    this.tbody = new Hrcbc.Controls.Control(null, {
        tag: "tbody"
    });	
    this.appendChild(this.tbody);		
    
    this.addRow = function(row, index) {
        if (!row || !(row instanceof Hrcbc.Controls.TableRow))
            row = new Hrcbc.Controls.TableRow();
        row.table = this;
        this.tbody.addChild(row, index);
        row.show();
        if (Object.isNull(index))
            index = this.rows.length;
        this.rows.splice(index, 0, row);
		return row;
    };
    
    this.removeRow = function(row) {
        if (typeof (row) == "number")
            row = this.rows[row];
        if (row instanceof Hrcbc.Controls.TableRow) {
            for (var i = 0; i < row.cells.length; i++)
                row.removeCell(i);
            var rowIndex = this.rows.indexOf(row);
            this.rows.splice(rowIndex, 1);
            row.destory();
            delete row;
        }
    };
    
    this.addColumn = function(column, index) {
        if (index == null || index == undefined || typeof (index) != "number")
            index = this.columns.length;
        this.columns.splice(index, 0, column);
		var headerCell = this.headerRow.addCell(new Hrcbc.Controls.TableCell({
            table: this,
            column: column,
            row: this.rows[i],
			tag : "th"
        }),index);	
		headerCell.setHtml(column.name);	
        for (var i = 0; i < this.rows.length; i++) {
            this.rows[i].addCell(new Hrcbc.Controls.TableCell({
                table: this,
                column: column,
                row: this.rows[i]
            }), index);			
        };
    };
    
    this.removeColumn = function(column) {
        if (typeof (column) == "object")
            column = this.columns.indexOf(column);
        else if (typeof (column) == "string") {
            for (var i = 0; i < this.columns.length; i++) {
                if (this.columns[i].name == column)
                    column = i;
            }
        }
        if (typeof (column) == "number") {
            this.columns.splice(column, 1);
            for (var i = 0; i < this.rows.length; i++)
                this.rows[i].removeCell(column);
        }
    };
    
    this.column = function(c) {
        if (typeof (c) == "number")
            return this.columns[c];
        if (typeof (c) == "string") {
            for (var i = 0; i < this.columns.length; i++) {
                if (this.columns[i].name == c)
                    return this.columns[i];
            }
        }
        return null;
    };
    
    this.cell = function(rowIndex, column) {
        var row = this.rows[rowIndex];
        if (row) return row.cell(column);
        return null;
    };
	
    this.merge = function(cell, rowspan, colspan) {
        if (cell && cell.table == this) {
        	var row = cell.row;
			if(!row) return;
			if(!rowspan) rowspan = 1;
			if(!colspan) colspan = 1;
			var rowIndex = this.rows.indexOf(row);
			var colIndex = row.cells.indexOf(cell);
			if(rowIndex + rowspan > this.rows.length)
				rowspan = this.rows.length - rowIndex;
			if(colIndex + colspan > this.columns.length)
			    colspan = this.columns.length - colIndex;
			cell.setAttribute("rowSpan",rowspan);
			cell.setAttribute("colSpan",colspan);
			for(var i=0; i<rowspan; i++) {
				for(var n=0; n<colspan; n++) {
					var c =this.cell(rowIndex + i,colIndex + n); 
					if(!c || c == cell) continue;
					this.rows[rowIndex + i].removeCell(colIndex + n); 
				}
			}
        }
    };
    
    this.apply = this.apply.callback(function() {
        if (this.$INITED) {
            if (!Object.isNull(this.cellspacing))
                this.setAttribute("cellspacing", this.cellspacing);
            if (!Object.isNull(this.cellpadding))
                this.setAttribute("cellpadding", this.cellpadding);
            if (!Object.isNull(this.border))
                this.setAttribute("border", this.border);
			if(this.showHeader == true)
				this.headerRow.show();
			else
				this.headerRow.hide();

        }
    }, null, this);    
	this.headerRow = new Hrcbc.Controls.TableRow({
		type : "header",
		table : this
	});	
	this.tbody.addChild(this.headerRow);
	this.headerRow.show();
	this.apply();
});
Class.load("Hrcbc.Controls.Control");

Class.register("Hrcbc.Controls.TreeNode",function( args){
	this.base = Hrcbc.Controls.Control;
	this.base(null,(args || {}).extend({
		element : "<li class=\"control_tree_node\" cname=\"treeNode\"><div class=\"control_tree_nodeText\" cname=\"nodeText\"></div><ul class=\"control_tree_nodeList\" cname=\"nodeList\"></ul></li>",
		skin : "tree"
		
	},false).extend({
		skinOptions: {
			loadHtml: false
		}
	}));	
	this.childNodes = [];	
	this.nodeText = this.findControl("//*[@cname=nodeText]");
	this.nodeList = this.findControl("//*[@cname=nodeList]");	
	this.status = "expand"; 	this.root = null;
	this.showImage = true;
	this.imageUrl = null;	
	this.showCheckBox = true;
	this.depth = 0;
	this.parentNode = null;
	Hrcbc.Event.addDispatcher(this);
	
	this.appendChild = function(childNode) {
		this.nodeList.appendChild(childNode);
		this.childNodes.push(childNode);
		childNode.depth = this.depth + 1;
		childNode.parentNode = this;
		childNode.root = this.root;		
	};
	
	this.removeChild = function(childNode) {
		this.nodeList.removeChild(childNode);
		this.childNodes.remove(childNode);
	};
	
	this.expand = function() {		
		this.setStatus("expand");
		this.nodeList.show();
	};
	
	this.expandAll = function() {
		this.expand();
		for(var i=0; i<this.childNodes.length; i++) {
			this.childNodes[i].expandAll();	
		}		
	};
	
	this.collapse = function() {
		this.setStatus("collapse");
		this.nodeList.hide();
	};
	
	this.collapseAll = function() {
		this.collapse();
		for(var i=0; i<this.childNodes.length; i++) {
			this.childNodes[i].collapseAll();
		}
	};
	
	this.toggle = function() {
		if(this.status == "expand")
			this.collapse();
		else 
			this.expand();
	};
	
	this.toggleAll = function() {
		this.toggle();
		for(var i=0; i<this.childNodes.length; i++) {
			this.childNodes[i].toggleAll();
		}
	};
	
	this.setText = function(text,href) {
		this.text = text || this.text || "";
		this.href = href || this.href;
		if(this.controlText) {
			this.controlText.setHtml("<a href=\"{1}\">{0}</a>".format(this.text,this.href || "javascript:;"),true);
		}
	};
	
	this.setStatus = function(status) {
		this.status = status;
		if(this.indent){
			this.indent.setCssClass(this.getIndentClass(this));
		}
		if(this.controlImage) {
			this.controlImage.setCssClass(this.getImageClass());
			this.controlImage.setStyle(this.getImageStyle());
		}	
		if(this.statechange)
			this.statechange(this);	
	};
	
	this.render = function() {
		for(var i=0; i<this.childNodes.length; i++) 
			this.childNodes[i].render();
		if(!this.nodeText) return;
		if (this.indent) {
			this.indent.distory();
			delete this.indent;
		}
		if(this.checkbox) {
			this.checkbox.distory();
			delete this.checkbox;
		}
		if(this.controlText) {
			this.controlText.distory();
			delete this.controlText;
		}
		if(this.controlImage) {
			this.controlImage.distory();
			delete this.controlImage;
		}
		var treeNode = this,sHtml = "",className;
		var imageHtml = "<img src=\""+ Hrcbc.path() + Hrcbc.blankImageUrl +"\" class=\"{0}\" {1} />";
		while(treeNode.parentNode && treeNode.parentNode != this.root) {
			sHtml = imageHtml.format(this.getIndentClass(treeNode.parentNode),"") + sHtml;
			treeNode = treeNode.parentNode;
		}
		sHtml += imageHtml.format(this.getIndentClass(this),"cname=\"indent\"");
		if(this.showCheckBox) 
			sHtml += "<input class=\"tree_checkbox\" type=\"checkbox\" />";		
		if(this.showImage) 
			sHtml += imageHtml.format(this.getImageClass(),"cname=\"image\" style=\"{0}\"".format(this.getImageStyle()));
		sHtml += "<span class=\"control_tree_node_text\" cname=\"text\"></span>";
		this.nodeText.setHtml(sHtml);		
		if(this.hasChildNodes) {
			this.indent = this.nodeText.findControl("//*[@cname=indent]");
			if(this.indent) {
				this.indent.setStyle("cursor","pointer");
				Hrcbc.Event.addEventListener(this.indent.element,"click",function() {
					this.toggle();					
				}.delegate(this));
			}
		}
		this.checkbox = this.nodeText.findControl("//input[@type=checkbox]");
		if(this.checkbox) {
			Hrcbc.Event.addEventListener(this.checkbox.element,"click",function(){
				var checked = this.checkbox.element.checked;
				for(var i=0; i<this.childNodes.length; i++) {
					this.childNodes[i].setAllChecked(checked);
				}
				if (checked) {
					var treeNode = this.parentNode;
					while (treeNode != this.root) {
						treeNode.setChecked(true);
						treeNode = treeNode.parentNode;
					}
				}
			}.delegate(this));
		}
		this.controlText = this.nodeText.findControl("//*[@cname=text]");
		if(this.controlText) {
			Hrcbc.Event.addEventListener(this.controlText.element,"click",function() {
				if(this.click) this.click(this);
			}.delegate(this));
			Hrcbc.Event.addEventListener(this.controlText.element,"dblclick",function() {
				this.toggle();					
			}.delegate(this));
			this.setText();
		}
		this.controlImage = this.nodeText.findControl("//*[@cname=image]");
	};
	
	this.getIndentClass = function(treeNode) {
		var className = ["control_tree_node_indent"];
		if(treeNode.parentNode && treeNode == treeNode.parentNode.lastChild()) { 			if(treeNode == this) {					if(!treeNode.hasChildNodes())
					className.push("indent_last_nochild");			
				else 
					className.push(treeNode.status == "expand" ? "indent_last_haschild_expand" : "indent_last_haschild_collapse");
			}
			else {
				className.push("indent_last_blank");
			}
		}
		else {
			if (treeNode == this) {
				if (!treeNode.hasChildNodes()) 
					className.push("indent_nochild");
				else 
					className.push(treeNode.status == "expand" ? "indent_haschild_expand" : "indent_haschild_collapse");
			}
			else {
				className.push("indent_blank");
			}
		}
		return className.join(' ');		
	};
	
	this.getImageClass = function() {
		var className = ['tree_image'];
		if(!this.imageUrl) {
			if(this.hasChildNodes()) 
				className.push(this.status == "expand" ? "tree_image_folder_open":"tree_image_folder");
			else
				className.push("tree_image_file");
		}
		return className.join(' ');
	};
	
	this.getImageStyle = function() {
		if(this.imageUrl) {
			return "background-image:url({0});".format(this.imageUrl);
		}
	};
	this.select = function(isSelected) {
		
	};
	this.selected = function() {		
	};
	
	this.setChecked = function(isChecked) {		
		if(!this.checkbox) return;
		this.checkbox.element.checked = isChecked;
	};
	this.setAllChecked = function(isChecked) {
		this.setChecked(isChecked);
		for(var i=0; i<this.childNodes.length; i++) {
			this.childNodes[i].setAllChecked(isChecked);
		}
	};
	
	this.checked = function() {		
		if(!this.checkbox) return false;
		return this.checkbox.element.checked;
	};
	
	this.lastChild = function() {
		return this.childNodes.last();
	};
	
	this.firstChild = function() {
		return this.childNodes.first();
	};
	
	this.hasChildNodes = function() {
		return this.childNodes.length > 0;
	};
	
	this.getNodePath = function( separator) {
		separator = separator || "/";
		if(this.parentNode == this.root) return this.text;
		else return this.parentNode.getNodePath(separator) + separator + this.text;
	};
	this.collapse();
});

Class.load("Hrcbc.Controls.Control");
Class.load("Hrcbc.Controls.TreeNode");



Class.register("Hrcbc.Controls.Tree", function(args) {
    this.base = Hrcbc.Controls.Control;
    this.base(null, (args || {}).extend({
        data: null,
        dataUrl: null,
        xpath: null,
        showCheckBox: true,
        status: "expand",
        showImage: true,
        $DATA_NAMES: {
            text: 'text',
            image: 'image',
            id: 'id',
            data: 'data'
        },
        element: '<div><div cname="txtTitle"></div><ul class="control_tree_nodeList" cname="treeList"></ul></div>'
    }, false));
    this.txtTitle = this.findControl("//*[@cname=txtTitle]");
    this.treeList = this.findControl("//*[@cname=treeList]");
    this.childNodes = [];
    this.parentNode = this.root = this;
    Hrcbc.Event.addDispatcher(this);
    
    this.appendChild = function(childNode) {
        this.treeList.appendChild(childNode);
        this.childNodes.push(childNode);
        childNode.parentNode = this;
    };
    
    this.lastChild = function() {
        return this.childNodes.last();
    };
    
    this.firstChild = function() {
        return this.childNodes.first();
    };
    
    this.hasChildNodes = function() {
        return this.childNodes.length > 0;
    };
	
    this.expandAll = function() {
        for (var i = 0; i < this.childNodes.length; i++) {
            this.childNodes[i].expandAll();
        }
    };
    
    this.collapseAll = function() {
        for (var i = 0; i < this.childNodes.length; i++) {
            this.childNodes[i].collapseAll();
        }
    };
    
    this.expand = function() {
        this.setStatus("expand");
        for (var i = 0; i < this.childNodes.length; i++) {
            this.childNodes[i].expand();
        }
    };
    
    this.collapse = function() {
        this.setStatus("collapse");
        for (var i = 0; i < this.childNodes.length; i++) {
            this.childNodes[i].collapse();
        }
    };
	 
    this.setStatus = function(status) {
        this.status = status;
    };
    
    this.createTree = function(data, treeNode) {
        if (data instanceof Array) {
            var parentNode = treeNode || this;
            for (var i = 0; i < data.length; i++) {
                var node = this.createNode(data[i]);
                parentNode.appendChild(node);
                var names = data.DATA_NAMES || this.$DATA_NAMES;
                if (data[i][names.data])
                    this.createTree(data[i][names.data], node);
            };
        }
    };
		
    this.render = function() {
        for (var i = 0; i < this.childNodes.length; i++) {
            this.childNodes[i].render();
        }
        if (this.status) 
            this.status == "expand" ? this.expand() : this.collapse();
    };
    
    this.createNode = function(data) {
        var names = data.DATA_NAMES || this.$DATA_NAMES;
        var treeNode = new Hrcbc.Controls.TreeNode();
        treeNode.root = this;
        treeNode.text = data[names["text"]];
        treeNode.showImage = this.showImage;
        treeNode.showCheckBox = this.showCheckBox;
        Hrcbc.Event.addEventListener(treeNode, "click", function(node) {
            if (this.click) {
                this.click(node);
            }
        } .delegate(this));
        return treeNode;
    };
    
    this.loadData = function(url, treeNode) {
        Hrcbc.AjaxRequest.getText(url, true, function(xmlHttp) {
            try {
                if (xmlHttp.responseXML)
                    this.createTree(Hrcbc.Xml.parseJSON(xmlHttp.responseXML, this.xpath), treeNode);
                else
                    this.createTree(xmlHttp.responseText.parseJSON(), treeNode);
                if (treeNode)
                    treeNode.render();
                else
                    this.render();
                if (this.load)
                    this.load(this);
            } catch (e) { }
        } .delegate(this));
    };
    if (this.data) {
        this.createTree(this.data);
        this.render();
    }
    else if (this.dataUrl) {
        this.loadData(this.dataUrl);
    }
});
Class.load("Hrcbc.Controls.Control");
Class.load("Hrcbc.Validate");

window.onerror = function() {
    return true;
};

Class.register("Hrcbc.Controls.Validator", function(element, args) {
    if (!args) args = {};
    if (!args.skin) args.skin = "validator";
    if (!args.tag) args.tag = "span";
    if (!args.skinOptions) args.skinOptions = { loadHtml: false };
    if (!element && !args.skinHtml && !args.skinOptions.loadHtml)
        args.skinHtml = "<span><span class=\"message\" cname=\"message\"></span></span>";
    if (!args.rightCssClass) args.rightCssClass = "control_validator_right";
    if (!args.errorCssClass) args.errorCssClass = "control_validator_error";
    if (!args.cssClass) args.cssClass = "control_validator_default";
    this.base = Hrcbc.Controls.Control;
    this.base(element, args);
    if (this.object && !this.object.$ISCONTROL)
        this.object = new Hrcbc.Controls.Control(this.object);
    if (this.object && this.$ISNEWCREATED)
        this.object.insertAfter(this.element);
    this.description = this.description || "&nbsp;";
    this.rightMessage = this.rightMessage || "&nbsp;";
    this.errorMessage = this.errorMessage || "&nbsp;";
    this.controlMessage = this.controlMessage || this.findControl("//*[@cname=message]");
    if (this.controlMessage && this.description) {
        this.controlMessage.setHtml(this.description);
    }
    this.eventName = this.eventName || ["blur"];
    this.attributeName = this.attributeName || "value";
    this.groupName = this.groupName || "default";
    this.isNullable = this.isNullable || false;
    this.isValid = true;
    this.datatype = null;
    this.isAlert = this.isAlert || false;
    var _this = this;
    
    this.validate = function() {
        if (!this.element) return;
        var testValue = null;
        if (this.object) testValue = this.object.getAttribute(this.attributeName);
        this.isValid = true;
        if (!this.method && this.regexp) {
            var _this = this;
            this.method = function(value) {
                var regexp = typeof (_this.regexp) == "string" ? new RegExp(String(_this.regexp), "ig") : _this.regexp;
                return regexp.test(value)
            };
        }
        else if (!this.method) {
            this.method = Hrcbc.Validate.getMethod(this.datatype || "string");
        }
        if (testValue == null || !this.method(testValue))
            this.isValid = (testValue == null || String(testValue).isEmpty()) && this.isNullable == true;
        this.show(this.isValid);
        if (this.callBack) this.callBack.apply(this);
        return this.isValid;
    };
    
    this.show = this.show.callback(function(isValid) {
        this.removeCssClass(this.rightCssClass);
        this.removeCssClass(this.errorCssClass);
        this.addCssClass(Object.isNull(isValid) ? "" : (isValid ? this.rightCssClass : this.errorCssClass));
        if (this.controlMessage) {
            this.controlMessage.setHtml(Object.isNull(isValid) ? this.description : (this.isValid ? this.rightMessage : this.errorMessage));
            if (!this.isValid && this.isAlert) alert(this.message);
        }
        else if (!this.isValid) {
            alert(this.message);
        }
    }, null, this);
    if (this.eventName instanceof Array && this.object) {
        for (var i = 0; i < this.eventName.length; i++)
            this.addEventListener(this.eventName[i], function() { _this.validate(_this, arguments); }, this.object.element);
    }
});Class.load("Hrcbc.Controls.Control");

Class.register("Hrcbc.Controls.Window", function(args) {
    if (!args) args = {};
    if (!args.skin) args.skin = "window";
    if (!args.width) args.width = 500;
    if (!args.height) args.height = "auto";
    if (Object.isNull(args.maskable)) {
        args.maskable = true;
        args.maskOptions = { fullscreen: true };
    }
    this.base = Hrcbc.Controls.Control;
    this.base(null, args);
    this.header = null;
    this.titleControl = null;
    this.mainmenu = null;
    this.toolbar = null;
    this.tabControl = null;
    this.footer = null;
    this.contentControl = null;
    this.buttons = null;
    this.$INITCONTROLS = false;
    var $setStyle = this.setStyle;
    
    this.initControls = function() {
        this.header = this.findControl("//*[@cname=header]");
        this.mainmenu = this.findControl("//*[@cname=mainmenu]");
        this.toolbar = this.findControl("//*[@cname=toolbar]");
        this.tabControl = this.findControl("//*[@cname=tabcontrol]");
        this.contentControl = this.findControl("//*[@cname=content]");
        this.titleControl = this.findControl("//*[@cname=title]");
        this.footer = this.findControl("//*[@cname=footer]");
        this.stautsControl = this.findControl("//*[@cname=status]");
        this.buttons = {};
        this.buttons["close"] = this.findControls("//*[@cname=buttonClose]");
        for (var i = 0; i < this.buttons["close"].length; i++) {
            var closeButton = this.buttons["close"][i];
            if (!closeButton.$INITEVENT) {
                closeButton.addEventListener("click", this.hide.delegate(this), closeButton.element);
                closeButton.$INITEVENT = true;
            }
        }
        this.$INITCONTROLS = true;
    };
    
    this.setStyle = function(name, value) {
        if (/^width|height$/ig.test(name)) {
            if (name.toLowerCase() == "height" && value.toLowerCase() != "auto") if (this.contentControl) this.contentControl.setStyle("height", String(parseInt(value) - this.size(this.header).height - this.size(this.mainmenu).height - this.size(this.toolbar).height - this.size(this.tabControl).height - this.size(this.footer).height) + "px");
            else $setStyle.apply(this, [name, value]);
        }
        else $setStyle.apply(this, [name, value]);
    };
    
    this.setHtml = function(html, override) {
        if (Object.isNull(html) || String(html).isEmpty()) return;
        if (this.contentControl) this.contentControl.setHtml(html, override);
    };
    
    this.setContent = function(content, override) {
        this.setHtml(content || this.content, override);
    };
    
    this.setTitle = function(title) {
        var title = title || this.title;
        if (Object.isNull(title) || String(title).isEmpty()) return;
        if (this.titleControl) this.titleControl.setHtml(title, true);
    };
    
    this.setSkin = this.setSkin.callback(function(skinHtml) {
        this.$INITCONTROLS = false;
        this.initControls();
    }, null, this);
    this.initControls();
    this.setContent();
    this.setTitle();
    this.drag(true, this.titleControl || this.header || this.element);
});
Class.load("Hrcbc.Controls.Window");


Class.register("Hrcbc.Controls.WinForm",function(args){
	if(!args) args = {};
	if(!args.action) args.action = window.location.href;
	if(!args.enctype) args.enctype = "application/x-www-form-urlencoded";
	if(!args.target) args.target = "_self";
	if(!args.method) args.method = "post";
	if(Object.isNull(args.asyncMode)) args.asyncMode = true;
	if(!args.formHtml) args.formHtml = "<form name=\"{0}\" id=\"{0}\" class=\"control_winform\" action=\"{1}\" target=\"{2}\" method=\"{3}\" enctype=\"{4}\">{5}</form>";
	if(!args.listHtml) args.listHtml = "<div class=\"control_winform_title\">{0}</div><table class=\"control_winform_list\" cellpadding=\"2\" cellspacing=\"0\"><tbody>{1}</tbody></table>";
	if(!args.rowHtml) args.rowHtml = "<tr class=\"control_winform_row\"><td class=\"control_winform_row_title wrap\" title=\"{0}\">{0}:</td><td class=\"control_winform_row_field\">{1}</td><td class=\"control_winform_row_description\">{2}</td></tr>";
	if(!args.msgHtml) args.msgHtml = "<span id=\"{0}\" class=\"control_winform_message\"></span>";	   		
	this.base = Hrcbc.Controls.Window;
	this.base(args);	 	
	
	this.addField = function() {
		if(arguments.length == 0) return;
		var field = typeof(arguments[0]) == "object" ? arguments[0] : {
			name : arguments[0] || null,
			value : arguments[1] || null,
			type : arguments[2] || "string"
		};
		if(!field.name) return;
		if(!this.fields) this.fields = [];
		this.fields.push(field);
	};
	this.createField = function( field) {
		field.type = field.type || "string";
		switch(field.type.toLowerCase()) {
			default:
			case "string": {				
				return "<input type=\"text\" name=\"{0}\" class=\"input\" value=\"{1}\" />".format(field.name,field.value || "");
			}			
		};
		
	};
	this.createValidator = function( field) {
		return "";
	}
	this.show = this.show.callback(function() {
		var html = "";
		for(var i=0; i<this.fields.length; i++) {
			var field = this.fields[i];
			if(!field.name) continue;
			html += this.rowHtml.format((field.title || field.name),this.createField(field) + this.createValidator(field),field.description || "");
		}
		html = this.listHtml.format(this.formTitle || "",html);
		html = this.formHtml.format(this.id,this.action,this.target,this.method,this.enctype,html);
		this.setHtml(html); 
	},null,this);	
	this.show();
});

