(function($) {

    $.trim = function() {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    }

    $.isPercent = function() {
        return /^(\d*)(\.?)(\d*)%$/.test(this);
    }

})(String.prototype);

/*-------------------------------------------------------------------------------------------------*/

(function($) {
    var __alert__ = $.alert;
    $.alert = function() {
        var arg,s = "";
        for (var i = 0; i < arguments.length; i++) {
            s += arguments[i] + "\n";
        }
        __alert__(s);
    }
    delete __alert__;
})(window);

/*-------------------------------------------------------------------------------------------------*/

var JObj = {};
(function($) {

	var ATTR_UNIQUE_ID = '__JOBJ_UNIQUE_ID__';
	$.getUniqueIdAttr = function(){
		return ATTR_UNIQUE_ID;
	}
	
    if (!document.body)
        document.write("<body></body>");

    /*-------------------------------------------------------------------------------------------------*/
    $.isObject = function(p) {return "object" == typeof(p)}
    $.isFunction = function(p) {return p instanceof Function;}

    $.isRate = function(p) {
        if (typeof p != "string") return false;
        if (p.substr(p.length - 1, 1) != "%")
            return false;
        if (isNaN(p.substring(0, p.length - 1)))
            return false;
        return true;
    }

    $.toSource = function(obj) {
        if (Object.toSource)
            return obj.toSource();
        else {
            var v = [],o;
            for (o in obj) {
                if (o == "toSource")
                    continue;
                if (typeof obj[o] == "object")
                    v.push('"' + o + '":{}');
                else
                    v.push('"' + o + '":' + obj[o]);
            }
            return "({" + v.join(",") + "})";
        }
    }

    $.doFunction = function(fun) {
        var args = [],i;
        for (i = 1; i < arguments.length; i++) {
            args.push(arguments[i]);
        }
        return function() {
            fun.apply(null, args);
            delete args;
        };
    }

    $.getEvent = function(evt) {
        evt = window.event || evt;

        if (!evt) {
            var fun = $.getEvent.caller;
            while (fun != null) {
                evt = fun.arguments[0];
                if (evt && evt.constructor == Event)
                    break;
                fun = fun.caller;
            }
        }
        delete fun;
        return evt;
    }

    $.addEvent = function(obj, type, fun) {
        obj = $.$(obj);
        if (obj.attachEvent) {
            if (! /^on/.test(type))
                type = 'on' + type;
            obj.attachEvent(type, fun);
        } else if (obj.addEventListener) {
            if (/^on/.test(type))
                type = type.substr(2);
            obj.addEventListener(type, fun, false);
        }
        delete obj;
    }

    $.removeEvent = function(obj, type, fun) {
        obj = $.$(obj);
        if (obj.attachEvent) {
            if (! /^on/.test(type))
                type = 'on' + type;
            obj.detachEvent(type, fun);
        } else if (obj.addEventListener) {
            if (/^on/.test(type))
                type = type.substr(2);
            obj.removeEventListener(type, fun, false);
        }
        delete obj;
    }

    $.getUniqueId = function(obj) {
        obj = JObj.$(obj);
        if (obj == window) return "window";
        if (obj == document) return "document";

        var id = obj.getAttribute($.getUniqueIdAttr());
        if (id != null && id != "")
            return id;

        if (obj.uniqueID) id = obj.uniqueID;
        else id = (((new Date()).valueOf() * 100000) + Math.random() * 100000).toString(32);

        obj.setAttribute($.getUniqueIdAttr(), id);
        delete obj;
        return id;
    }

    /*-------------------------------------------------------------------------------------------------*/


    $.Browser = {};
    (function($, $$) {

        $.getFlashVersion = function() {
            var f = "-1",n = navigator;
            if (n.plugins && n.plugins.length) {
                for (var ii = 0; ii < n.plugins.length; ii++) {
                    if (n.plugins[ii].name.indexOf('Shockwave Flash') != -1) {
                        f = n.plugins[ii].description.split('Shockwave Flash ')[1];
                        break;
                    }
                }
            } else if (window.ActiveXObject) {
                for (var ii = 11; ii >= 2; ii--) {
                    try {
                        var fl = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + ii + "');");
                        if (fl) {
                            f = ii + '.0';
                            break;
                        }
                    } catch(e) {
                    }
                }
            }

            if (f == "-1") return f;
            else return f.substring(0, f.indexOf(".") + 2)
        }

        var n_ = navigator;

        var b = n_.appName;
        var ua = n_.userAgent.toLowerCase();
        $.userAgent = n_.userAgent;
        $.name = "Unknow";
        $.safari = ua.indexOf("safari") > -1;  // always check for safari & opera
        $.chrome = ua.indexOf('chrome') > -1;	// must under safari check;
        $.opera = ua.indexOf("opera") > -1;    // before ns or ie
        $.firefox = ua.indexOf('firefox') > -1; // check for gecko engine
        $.netscape = !$.firefox && !$.opera && !$.safari && (b == "Netscape");
        $.ie = !$.opera && (b == "Microsoft Internet Explorer");

        $.name = ($.ie ? "IE" : ($.firefox ? "Firefox" : ($.netscape ? "Netscape" : ($.opera ? "Opera" : ($.chrome ? "Chrome" : ($.safari ? 'Safari' :"Unknow"))))));
        
        switch ($.name) {
            case "Opera":
                $.fullVersion = n_.appVersion.split(" ")[0];
                $.os = n_.appVersion.split(";")[1];
                break;
            case "IE":
                $.fullVersion = ua.substr(ua.indexOf("msie") + 5).split(";")[0];
                break;
            case "Firefox":
                $.fullVersion = ua.substr(ua.indexOf("firefox") + 8);
                break;
            case "Safari":
                $.fullVersion = ua.substr(ua.indexOf("version") + 8).split(" ")[0];
                break;
            case 'Chrome':
            	$.safari = false;////
            	$.fullVersion = ua.substr(ua.indexOf('chrome') + 7).split(' ')[0];
            	break;
            case "Netscape":
                $.fullVersion = ua.substr(ua.indexOf("netscape") + 9);
                break;
            default:
                $.fullVersion = "-1";
        }
        $.version = parseFloat($.fullVersion);

        $.cookieEnabled = n_.cookieEnabled;
        $.javaEnabled = n_.javaEnabled();

        $.os = $.os || n_.platform;
        $.browserLang = n_.browserLange || n_.language;
        $.osLang = n_.language;

    })($.Browser, $);

    /*-------------------------------------------------------------------------------------------------*/

    $.Dom = {};
    (function($, $$) {

        $$.$ = $.$ = function(p, doc) {return $$.isObject(p) ? p : (doc || document).getElementById(p);}
        $$.$c = $.$c = function(tag) {return document.createElement(tag);}
        $$.$tag = $.$tag = function(tag, node) {return $$.$(undefined == node || null == node ? document : node).getElementsByTagName(tag);}
        $$.$name = $.$name = function(name, node) {return $$.$(undefined == node || null == node ? document : node).getElementsByName(name);}

        $$.$class = $.$class = function(className,obj) {
        	obj = $.$(obj) || document;
        	//if(obj.getElementsByClassName){
        	//	return obj.getElementsByClassName(className);
        	//}else{
        		var objs = obj.all || obj.getElementsByTagName("*");
        		var o,i,arr = [];
        		for (i = 0; o = objs[i]; i++) {
        			if (o.className == className) {
        				arr.push(o);
        			}
        		}
                delete objs;
        		return arr;
        	//}
        }

        $.getRuntimeStyle = function(obj, k, d) {
            var v = null;
            if (obj.currentStyle){
                k = k.replace(/\-(\w)/ig,function(){return arguments[1].toUpperCase();});
                if(k == 'float') k = 'styleFloat';//ie,opera
                v = obj.currentStyle[k];
            }else{
                if(k == 'styleFloat') k = 'float';
                k = k.replace(/[A-Z]/g,function(){return '-' + arguments[0].toLowerCase();});
                v = window.getComputedStyle(obj, null).getPropertyValue(k);
            }
            if ((v == 'auto' || v == '') && d != undefined) v = d;
            delete obj;
            return v;
        }

        $.getOpacity = function(obj) {
            if (JObj.Browser.ie) {
                var a = obj.style.filter.alpha;
                return a == undefined ? 100 : a;
            } else {
                return $.getRuntimeStyle(obj, 'opacity', 1) * 100;
            }
        }

    })($.Dom, $);

    var scripts = $.$tag("SCRIPT"),script,i;
    for (i = 0; script = scripts[i]; i++) {
        if ((/JObj\.js$/i).test(script.src)) {
            $.path = script.src.replace(/JObj\.js$/i, "");
            $.path == "" && ($.path = "./");
            break;
        }
    }
    delete scripts;
    delete script;

    /*-------------------------------------------------------------------------------------------------*/
    $.Style = {};
    (function($, $$) {

        var style = null;
        var styleSheet = null;
        $.addRule = $.insertRule = function(p, k, asNew) {
            if(asNew !== true){
                if (style == null) {
                    style = $$.$c("STYLE");
                    $$.$tag("HEAD")[0].appendChild(style);
                    styleSheet = style.styleSheet || style.sheet;
                }
            }else{
                style = $$.$c("STYLE");
                $$.$tag("HEAD")[0].appendChild(style);
                styleSheet = style.styleSheet || style.sheet;
            }

            if (styleSheet.addRule) {
                var rs = p.split(',');
                for(var i=0;i<rs.length;i++)
                    styleSheet.addRule(rs[i], k);
            } else if (styleSheet.insertRule) {
                styleSheet.insertRule(p + "{" + k + "}", styleSheet.cssRules.length);
            }
        }

        /**
         * 如果设置alpha,请设置 rule 为 alpha 或 opacity,值 取 1~100
         */
        var fixCss = function(){return arguments[1].toUpperCase();}
        
        $$.css = $.css = function(obj, rules) {
            obj = $$.$(obj);
            var rule;
            for (rule in rules) {
                //rule = rule.replace(/\-(\w)/ig,function(){return arguments[1].toUpperCase();});
                rule = rule.replace(/\-(\w)/ig,fixCss);
                if(rule =='float' && obj.currentStyle) rule = 'styleFloat';
                
                if(/alpha|opacity/.test(rule)){
                    if($$.Browser.ie){
                        obj.style.filter = 'alpha(opacity:' + rules[rule] + ')';
                    }else{
                        obj.style.opacity = rules[rule] / 100;
                    }
                }else{                	
                	obj.style[rule] = rules[rule] + ( /(width|height|positionX|positionY|top|left|right|bottom|fontSize)$/i.test(rule) && !isNaN(rules[rule]) ? 'px' : '')  
                }
            }
            delete obj;
        }

    })($.Style, $);
    /*-------------------------------------------------------------------------------------------------*/

    $.Xml = {};
    (function($, $$) {

        var ACTIVEXOBJECT_XMLHTTP = null;
        var ACTIVEXOBJECT_DOMDOCUMENT = null;
        
        if (!$$.Browser.ie) {
            Element.prototype.__defineGetter__("xml", function() {
                return (new XMLSerializer).serializeToString(this);
            });
        }

        $.getXMLHttp = function() {
            var xmlHttp = null;
            //if($$.Browser.ie && $$.Browser.version < 7){ //用IE7内置的 XMLHttpRequest 对象，不能加载本地文件．
            if ($$.Browser.ie) {
                var v = [/*'MSXML2.XMLHTTP.8.0', 'MSXML2.XMLHTTP.7.0',*/ 'MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP.2.6', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
                if (typeof(ACTIVEXOBJECT_XMLHTTP) == "string")
                    v[0] = ACTIVEXOBJECT_XMLHTTP;

                var v_;
                for (var i = 0; v_ = v[i]; i++) {
                    try {
                        xmlHttp = new ActiveXObject(v_);
                        ACTIVEXOBJECT_XMLHTTP = v_;
                        break;
                    } catch(e) {}
                }
                
            } else {
                xmlHttp = new XMLHttpRequest();
            }

            if (xmlHttp == null) {
                alert("你的系统不支持AJAX");
            }
            return xmlHttp;
        }


        $.getXMLDoc = function() {
            //DOMParser document.implementation
            if ($$.Browser.ie) {
                var doc = null;
                var v = ["Msxml2.DOMDocument.6.0","Msxml2.DOMDocument.5.0","Msxml2.DOMDocument.4.0","Msxml2.DOMDocument.3.0","MSXML2.DOMDocument"];
                if (typeof(ACTIVEXOBJECT_DOMDOCUMENT) == "string")
                    v[0] = ACTIVEXOBJECT_DOMDOCUMENT;

                var v_;
                for (var i = 0; v_ = v[i]; i++) {
                    try {
                        doc = new ActiveXObject(v_);
                        ACTIVEXOBJECT_DOMDOCUMENT = v_;
                        break;
                    } catch(e) {
                    }
                }
            } else if (document.implementation && document.implementation.createDocument) {
                doc = document.implementation.createDocument("", "doc", null);
            }

            return doc;
        }

        $.loadXML = $.parseXML = function(source) {
            var doc;
            if (window.DOMParser) {
                var parser = new DOMParser();
                doc = parser.parseFromString(source, "text/xml");
            } else {
                doc = $.getXMLDoc();
                doc.loadXML(source);
            }
            return doc;
        }

        $.getNodeAtt = function(pNode, pAtt) {
            try {
                return pNode.attributes.getNamedItem(pAtt).nodeValue;
            } catch(e) {
                //alert("前台调试错误：\n"+e.message+"\n当前节点不存在: "+pAtt+"这个属性");
                return false;
            }
        }

        $.extractNodes = function(pNode) {
            if (pNode.nodeType == 3)
                return null;
            var node,nodes = new Array();
            for (var i = 0; node = pNode.childNodes[i]; i++) {
                if (node.nodeType == 1 || node.nodeType == 4)
                    nodes.push(node);
            }
            return nodes;
        }

        $.getXML = $.serialize = function(pNode) {
            if (!pNode) return null;
            if (pNode.xml)
                return pNode.xml;
            else if (window.XMLSerializer)
                return (new XMLSerializer()).serializeToString(pNode);
        }

    })($.Xml, $);


    /*----------------------------------------------------------------------------------
     Ajax
     JObj.Ajax
     ----------------------------------------------------------------------------------*/
    $.Ajax = {};
    (function($, $$) {

        // AjaxObj
        var AjaxObj = function(rule, dataRule) {
            var $ = this;
            $.async = rule.async == undefined ? true : rule.async;//默认异步加载

            var prepareData = function() {
                if (dataRule == null) return null;

                var o;
                var s = [];
                for (o in dataRule) {
                    s.push( encodeURIComponent(o) + "=" + encodeURIComponent(dataRule[o]) );
                    //必须要： encodeURIComponent,否则，post 不成功！
                }
                s = s.join('&');

                if ($.method.toUpperCase() == "GET") {
                    $.url += ($.url.indexOf("?") > -1 ? "&" : "?") + s;
                    return null;
                } else
                    return s;
            }

            var ready = function() {
                $.url = rule.url;
                $.method = rule.method || "GET";
                $.data = prepareData();
                $.onSuccess = rule.onSuccess;
                $.onUnsuccess = rule.onUnsuccess;
                $.onError = rule.onError;
                $.onReady = rule.onReady;
            }

            $.xmlHttp = $$.Xml.getXMLHttp();

            var xmlHttp_onreadystatechange = function() {
                var http = $.xmlHttp;
                if (http.readyState == 4) {
                    switch (http.status) {
                        case 0:
                        case 200:
                            $$.isFunction($.onSuccess) ? $.onSuccess(http, 200, rule, dataRule) : null;
                            break;
                        default :
                            $$.isFunction($.onUnsuccess) ? $.onUnsuccess(http, http.status, rule, dataRule) : null;
                    }
                } else
                    $$.isFunction($.onWait) ? $.onWait(http, http.readyState, rule, dataRule) : null;
            }

            if ($.async)//如果同步加载，就不要 onreadystatechange 了
                $.xmlHttp.onreadystatechange = xmlHttp_onreadystatechange;

            $.send = function() {
                ready();
                $.xmlHttp.open($.method, $.url, $.async);
                $.xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                try {
                    $.xmlHttp.send($.data);
                } catch(e) {
                    $$.isFunction($.onError) ? $.onError(e) : alert(e.message);
                    return;
                }
                if (!$.async) {
                    xmlHttp_onreadystatechange();
                }
            }
        }

        $.send = function(rule, dataRule) {
            var ajax = new AjaxObj(rule, dataRule);
            ajax.send();
        }

    })($.Ajax, $)


    /*----------------------------------------------------------------------------------
     JObj.Loader
     ----------------------------------------------------------------------------------*/

    $.Loader = {};
    (function($, $$) {
        /*
         QUEUE[url] = {
         beginTime:开始加载的时间,
         endTime:加载成功的时间,
         time:请求次数
         }
         */

        var fp = document.createDocumentFragment();
        var styleSheet = null;

        var SUCCESS = {}; // 以载入，
        var FAILED = {}; // 加载出错
        var QUEUE = {}; // 队列，如果以载入，从 队列中删除，加入到 LOADED中

        $.getSuccess = function() {return eval($$.toSource(SUCCESS))};
        $.getFailed = function() {return eval($$.toSource(FAILED))};
        $.getQueue = function() {return eval($$.toSource(QUEUE))};

        $.getUrlHost = function(path) {
            var a = document.createElement("A");
            a.href = path;
            return a.hostname;
        }

        $.getFullPath = function(path) {
            if (!$$.Browser.ie) {
                var a = document.createElement("A");
                a.href = path;
                return a.href;
            } else {
                // 不能用 appendChild(a), return a.href; 这样得到的 href 依然是 path
                var div = $$.$c("DIV");
                div.innerHTML = "<a href='" + path + "' />";
                //div.innerHTML   "<A href=\"http://blog/js/js.php\"></A>"
                return div.innerHTML.match(/href=\"(.*)\"/)[1];
            }
        }

        var script_onreadystatechange = function(script, path, callBack) {
            // for ie,没有办法判断JS文件是否真的加载完成。
            if (script.readyState == "loaded") {
                SUCCESS[path] = QUEUE[path];
                SUCCESS[path].endTime = (new Date()).valueOf();
                delete QUEUE[path];
                $$.isFunction(callBack) ? callBack() : null;
            }
        }

        var script_onload = function(path, callBack) {
            SUCCESS[path] = QUEUE[path];
            SUCCESS[path].endTime = (new Date()).valueOf();
            delete QUEUE[path];
            $$.isFunction(callBack) ? callBack() : null;
        }

        var script_onerror = function(path, callBack) {
            FAILED[path] = QUEUE[path];
            FAILED[path].endTime = (new Date()).valueOf();
            delete QUEUE[path];
            $$.isFunction(callBack) ? callBack() : null;
        }

        var script_onSuccess = function(xmlHttp, status, rule, dataRule) {
            SUCCESS[rule.url] = QUEUE[rule.url];
            SUCCESS[rule.url].endTime = (new Date()).valueOf();
            delete QUEUE[rule.url];
            if (JObj.Browser.ie)
                window.execScript(xmlHttp.responseText);
            //else if(JObj.Browser.safari && JObj.Browser.version < 4)
            //	window.setTimeout(xmlHttp.responseText,0);
            else
                window.eval(xmlHttp.responseText);

            delete xmlHttp;
        }

        var script_onUnsuccess = function(xmlHttp, status, rule, dataRule) {
            FAILED[rule.url] = QUEUE[rule.url];
            FAILED[rule.url].endTime = (new Date()).valueOf();
            delete QUEUE[rule.url];
            $$.isFunction(rule.unsuccessCallBack) ? rule.unsuccessCallBack() : null;

            delete xmlHttp;
        }

        var script = function(path, async) {
            if (async === null) async = false;// 默认为同步加载			
            var p = $.getFullPath(path);
            var h = location.host != "" && location.host == $.getUrlHost(p);

            QUEUE[p] = {
                beginTime:(new Date().valueOf()),
                endTime:null,
                time:1
            };

            if (h || location.protocol == "file:") {
                $$.Ajax.send({
                    async:async, // true 异步加载，false 同步加载
                    method:"GET",
                    url:p,

                    onSuccess:script_onSuccess,
                    onUnsuccess:script_onUnsuccess
                });
            } else {
                var script = $$.$c("SCRIPT");
                script.src = p;

                if ($$.Browser.ie) {
                    script.onreadystatechange = $$.doFunction(script_onreadystatechange, p, succCallBack);
                } else {
                    script.onload = $$.doFunction(script_onload, p, succCallBack);
                    script.onerror = $$.doFunction(script_onerror, p, unsuccCallBack);
                }

                fp.appendChild(script);
            }
        }

        $.include = function(path, succCallBack, unsuccCallBack, async) {
            script(path, async);
        }

        $.includeOnce = function(path, succCallBack, unsuccCallBack, async) {
            var p = $.getFullPath(path);
            if (p in QUEUE || p in SUCCESS) return;
            script(path, async);
        }


        $.loadCss = function(cssFile) {
            if(document.createStyleSheet)
                document.createStyleSheet(cssFile);
            else{
                if (styleSheet == null) {
                    var style = $$.$c('STYLE');
                    $$.$tag("HEAD")[0].appendChild(style);
                    styleSheet = style.styleSheet || style.sheet;
                }
                styleSheet.insertRule("@import url('" + cssFile + "');", styleSheet.cssRules.length);
            }
        }

    })($.Loader, $);

    $.plugin = function(pluginName, async) {
        async = (async == undefined || async == null || async.toString() != true || async.toString() != false) ? false : async;
        $.Loader.includeOnce($.path + "plugins/" + pluginName + "/" + pluginName + ".js", null, null, async);
    }

    $.use = function(lib, async) {
        async = (async == undefined || async == null || async.toString() != true || async.toString() != false) ? false : async;
        $.Loader.includeOnce($.path + "lib/" + lib + ".js", null, null, async);
    }
})(JObj)