﻿// JavaScript
// jfp 09-05-13
// lib

var LIB_LOADED, NAMESPACES_LOADED;
if(!LIB_LOADED) {
    var isIE = (navigator.userAgent.indexOf("MSIE") != -1);
    var SVGNameSpace = "http://www.w3.org/2000/svg";
    
    function keyDown(event){
        event = event || window.event;
        var ele = event.target || event.srcElement;
	    if(event.keyCode==8 && ((ele.tagName!="INPUT" && ele.tagName!="TEXTAREA") || ele.readOnly))return false;
	    else if(event.ctrlKey && event.keyCode==13 && ele.tagName=="TEXTAREA") {
		    ele.value+="\n ";
		    event.keyCode=8;
	    }else if(event.keyCode==13) {
	        if(ele.tagName=="INPUT" && ele.type=="submit")
	            return true;
	        else
	            window.event.keyCode=9;
	    }
    }
    document.onkeydown=keyDown;

    function focusIn(){
	    if((event.srcElement.tagName=="INPUT"&&(event.srcElement.type=="text"||event.srcElement.type=="password"||event.srcElement.type=="file"))||event.srcElement.tagName=="TEXTAREA"){
		    if(event.srcElement.readOnly)return;
		    if(typeof(event.srcElement.style.backgroundColor) == "string" && event.srcElement.style.backgroundColor != "")
		        event.srcElement.backgroundColorTemp = event.srcElement.style.backgroundColor;
		    event.srcElement.style.backgroundColor="#FFFFCC";
	    }
    }
    function focusOut(){
	    if((event.srcElement.tagName=="INPUT"&&(event.srcElement.type=="text"||event.srcElement.type=="password"||event.srcElement.type=="file"))||event.srcElement.tagName=="TEXTAREA"){
		    event.srcElement.style.background=(typeof(event.srcElement.backgroundColorTemp) == "string") ? event.srcElement.backgroundColorTemp : "#FFFFFF";
	    }
    }
    document.onfocusin=focusIn;
    document.onfocusout=focusOut;
    
    function $(id){
        if(typeof(id)=="object") return id;
        else {
            if(id.indexOf(",") > -1) {
                var a = id.split(","), b = [];
                for(var i=0,len=a.length; i<len; i++) {
                    if(a[i] != "")
                        b[b.length] = document.getElementById(a[i])
                }
                return b;
            }else
                return document.getElementById(id);
        }
    }
    function $N(name){return document.getElementsByName(name);}

    var $A = Array.from = function(iterable) {
      if (!iterable) return [];
      if (iterable.toArray) {
        return iterable.toArray();
      } else {
        var results = [];
        for (var i = 0, length = iterable.length; i < length; i++)
          results.push(iterable[i]);
        return results;
      }
    }

    // 创建一个页面元素tag
    function $C(tag, pro) {
        var ele = document.createElement(tag);
        $Set(ele, pro);
        return ele;
    }

    // 创建一个页面元素tag
    function $NS(tag, pro, ns) {
        var ele = document.createElementNS((typeof ns == "undefined" ? SVGNameSpace : ns), tag);
        $Set(ele, pro);
        return ele;
    }

    // 把o添加到p对象中
    function $To(ele, parent, node) {
	    if(ele && parent) {
	        if(typeof node != "undefined") {
	            if(typeof node == "number" && node > -1 && node < parent.children.length)
	                node = parent.children[node];
	            if(!node) parent.appendChild(ele);
	            else parent.insertBefore(ele, node);
	        }else parent.appendChild(ele);
		    return ele;
	    }else {
		    return null;
	    }
    }

    // 删除指定元素
    function $D(ele, parent) {
        if(!parent) parent = ele.parentNode;
        if(parent && ele && parent.removeChild)
            parent.removeChild(ele);
    }

    // 设置指定对像的属性
    function $Set(obj, pro) {
        if(obj && typeof pro == "object") {
		    for(property in pro)
			    obj[property] = pro[property];
        }
        return obj;
    }

     /* 
     * @parent 查找的父节点
     * @tagName 标签名称
     * @className 样式类名称
     */
    var $css = function(parent, tagName, className) {
	    var ele = $(parent).getElementsByTagName(tagName);
	    if (!ele) {
		    return null;
	    }
	    var ret = [];
	    for (var i=0; i<ele.length; i++) {
		    if (ele[i].className == className) {
			    ret[ret.length] = ele[i];
		    }
	    }
	    if (ret.length == 1) {
		    return ret[0];
	    } else {
		    return ret;
	    }
    }

    /**
     * 取得激发事件的对象
     * @e event对象
     * @bubble 是否保留事件冒泡
     */
    function $ele(event, bubble) {
	    event = event || window.event;
	    if(!event)return null;
	    if (typeof bubble != "undefined" && !bubble) {
		    cancelBubble(event);
	    }
	    return event.target || event.srcElement;
    }

    //取消事件冒泡
    function cancelBubble(event, cancel) {
        event = event || window.event;
        if(typeof cancel == "undefined" || cancel) {
            if(event.stopPropagation)
                event.stopPropagation();
            else
                event.cancelBubble = true;
        }else {
            if(event.startPropagation)
                event.startPropagation();
            else
                event.cancelBubble = false;
        }
    }

    // 取得指定节点的绝对 x 坐标
    function absoluteX(ele, extAbsolute) {
	    var x = ele.offsetLeft;
	    while (ele = ele.offsetParent) {
	        if(!extAbsolute && ((ele.currentStyle && ele.currentStyle.position) == "absolute" || ele.style.position == "absolute")) {break;}
		    x += ele.offsetLeft;
	    }
	    return x;
    }

    // 取得指定节点的绝对 y 坐标
    function absoluteY(ele, extAbsolute) {
	    var y = ele.offsetTop;
	    while (ele = ele.offsetParent) {
	        if(!extAbsolute && ((ele.currentStyle && ele.currentStyle.position == "absolute") || ele.style.position == "absolute")) {break;}
		    y += ele.offsetTop;
	    }
	    return y;
    }

    // 事件名
    var $EventName;
    if(!$EventName)
	    $EventName = new function() {
		    var isIE = (navigator.userAgent.indexOf("MSIE") != -1);
		    this.click       = isIE ? "onclick" : "click";
		    this.dblclick    = isIE ? "ondblclick" : "dblclick";
		    this.mousedown   = isIE ? 'onmousedown': 'mousedown';
		    this.mousemove   = isIE ? 'onmousemove' : 'mousemove';
		    this.mouseup     = isIE ? 'onmouseup' : 'mouseup';
		    this.mousewheel  = isIE ? 'onmousewheel' : 'DOMMouseScroll';
		    this.resize      = isIE ? 'onresize' : 'resize';
		    this.keydown     = isIE ? "onkeydown" : "keydown";
		    this.keypress    = isIE ? "onkeypress" : "keypress";
		    this.keyup       = isIE ? "onkeyup" : "keyup";
		    this.dragstart   = isIE ? "ondragstart" : "dragstart";
	    };

    // 绑定事件监听方法
    function $attachEvent(obj, eventName, oListener){
        if(obj.attachEvent){
            obj.attachEvent(eventName, oListener);
        }
        else if(obj.addEventListener){
            obj.addEventListener(eventName, oListener, false);
        }
        else{
            return false;
        }
    }

    // 删除事件监听方法
    function $detachEvent(obj, eventName, oListener){
        if(obj.detachEvent){
            obj.detachEvent(eventName, oListener);
        }
        else if(obj.removeEventListener){
            obj.removeEventListener(eventName, oListener, false);
        }
        else{
            return false;
        }
    }

    // 定义通用类创建对象
    var Class;
    if(!Class){
	    Class = {
		    create: function() {
				    return function() {
				        if(this.initialize)
					        return this.initialize.apply(this, arguments);
				    }
		    }
	    }
    }

    // 对象原型扩展
    if(!Object.extend){
	    Object.extend = function(destination, source) {
		    for (property in source) {
			    destination[property] = source[property];
		    }
		    return destination;
	    }
    }

    //扩充 Array
    Object.extend(Array.prototype, {
        indexOf : function(v){ // 从起始位置查找指定元素的索引
            for(var i=0; i<this.length; i++)
                if(this[i] === v)
                    return i;
            return -1;
        },
        lastIndexOf : function(v) { // 从结尾查找指定元素的索引
            for(var i = this.length; i-- && this[i] !== v;);
            return i;
        },
        remove : function(v) { // 从数组中删除指定元素
            var index = this.indexOf(v);
            if(index != -1)
                this.splice(index, 1);
        },
        insertAt : function(index, value) { //在数组指定位置插入元素
            this.splice(index, 0, value);
        },
        removeAt : function(index) { // 删除数组指定位置的元素
            this.splice(index, 1);
        },
        map : function(fun/*, thisp*/) {// 对数组中的每个元素都执行一次指定的函数（callback），并且以每次返回的结果为元素创建一个新数组
            var len = this.length;
            if (typeof fun != "function")
                return null;
            var res = new Array(len);
            var thisp = arguments[1];
            for (var i = 0; i < len; i++) {
                if (i in this)
                    res[i] = fun.call(thisp, this[i], i, this); // 回调函数可以有三个参数：当前元素，当前元素的索引和当前的数组对象
            }
            return res;
        },
        some : function(fun/*, thisp*/) { // 在指定数组中执行指定函数，函数返回值为true时，则返回true，否则最终返回false
            var len = this.length;
            if (typeof fun != "function")
                return false;
            var thisp = arguments[1];
            for (var i = 0; i < len; i++) {
                if (i in this && fun.call(thisp, this[i], i, this))
                    return true;
            }
            return false;
        },
        filter : function(fun/*, thisp*/) { // 用指定的函数过滤数组元素，返回值为true的将被保留到新数组
            var len = this.length;
            if (typeof fun != "function")
                return null;
            var res = new Array();
            var thisp = arguments[1];
            for (var i = 0; i < len; i++) {
                if (i in this) {
                    var val = this[i];
                    if (fun.call(thisp, val, i, this))
                        res.push(val);
                }
            }
            return res;
        },
        first : function(fun/*, thisp*/) { // 用指定的函数查找数组元素，返回第一个值为true的数组元素
            var len = this.length;
            if (typeof fun != "function")
                return null;
            var thisp = arguments[1];
            for (var i = 0; i < len; i++) {
                if (i in this) {
                    var val = this[i];
                    if (fun.call(thisp, val, i, this))
                        return val;
                }
            }
        },
        every : function(fun/*, thisp*/) { // 用指定的函数判断数组中每个元素是否都满足条件，如果有一个返回false，则返回false，否则最终返回true
            var len = this.length;
            if (typeof fun != "function")
                return false;
            var thisp = arguments[1];
            for (var i = 0; i < len; i++) {
                if (i in this && !fun.call(thisp, this[i], i, this))
                    return false;
            }
            return true;
        },
        forEach : function(fun/*, thisp*/) { // 对数组中的每个元素都执行一次指定的函数
            var len = this.length;
            if (typeof fun != "function")
                return;

            var thisp = arguments[1];
            for (var i = 0; i < len; i++) {
                if (i in this)
                    fun.call(thisp, this[i], i, this);
            }
        },
        shuffle : function() { // 打乱数组
            for(var j, t, i = this.length; i; j = parseInt(Math.random() * i), t = this[--i], this[i] = this[j], this[j] = t);
        }
    });
    function arrIndexOf(arr, obj) {
        for(var i = 0; i < arr.length; i++) { 
            if (arr[i] === obj) { 
                return i; 
            } 
        } 
        return -1;
    }
    function arrRemove(arr, obj) {
        var index = arrIndexOf(arr, obj);   

        if (index !== -1) {   
            arr.splice(index, 1);   
        }
    }
    
    // 扩展 Function
    Object.extend(Function.prototype, {
        bind : function() {
          var __method = this, args = $A(arguments), object = args.shift();
          return function() {
            return __method.apply(object, args.concat($A(arguments)));
          }
        },
        bindWithEvent : function(object) {
          var __method = this, args = $A(arguments), object = args.shift();
          return function(event) {
            return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
          }
        },
        delay : function() { //delay(time, object, args);
            var __method = this,
            args = $A(arguments),
            time = args.shift(),
            object = args.shift();
            var __callBack = function() {
                return __method.apply(object, args);
            }
            return window.setTimeout(__callBack, time);
        }
    });
    
    Object.extend(String.prototype, {
        trim : function() {
            return this.replace(/^\s+|\s+$/g, "");
        },
        repeat : function(n) {
            var s = "";
            for(i=0; i< n; i++)
                s += this;
            return s;
        },
        format : function() { // 用参数序列替换原字符串的匹配 {i}
            if(arguments.length == 0)
                return this;
                
            var reg = /{(\d+)?}/g;
            var args = arguments;
            return this.replace(reg, function($0, $1) {
                return args[parseInt($1)];
            });
        },
        startsWith : function(str) {
            var reg = new RegExp("^" + str);
            return reg.test(this);
        },
        endsWith : function(str) {
            var reg = new RegExp(str + "$");
            return reg.test(this);
        },
        escape : function() { // 编码非法字符
            return this.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&#34;").replace(/'/g, "&#39;");
        },
        escapeRegExp : function() {
            return this.replace(/(\$|\(|\)|\*|\+|\.|\[|\?|\\|\^|\{|\|)/g, "\\$1").replace(/\r/g, "\\r\?").replace(/\n/g, "\\n");
        }
    });
    
    Object.extend(Number.prototype, {
        round : function(dot) {
            return Math.round(this * Math.pow(10, dot)) / Math.pow(10, dot);
        }
    });

    if(window.HTMLElement) {
	    HTMLElement.prototype.__defineGetter__("children", 
		    function () { 
			    var returnValue = new Object(); 
			    var number = 0; 
			    for (var i=0; i<this.childNodes.length; i++) { 
				    if (this.childNodes[i].nodeType == 1) { 
					    returnValue[number] = this.childNodes[i]; 
					    number++; 
				    } 
			    } 
			    returnValue.length = number; 
			    return returnValue; 
		    } 
	    ); 
	    HTMLElement.prototype.swapNode = function(node) { 
		    var parent = this.parentNode;//父节点 
		    var t1 = this.nextSibling;//两节点的相对位置 
		    var t2 = node.nextSibling; 
		    if(t1) parent.insertBefore(node, t1); 
		    else parent.appendChild(node); 
		    if(t2) parent.insertBefore(this, t2); 
		    else parent.appendChild(this); 
	    } 
    }
    
    //获取日期字符串
    function getDateStr (){
	    var d = new Date();
	    return d.toLocaleDateString() + ' 星期' + '日一二三四五六'.charAt(d.getDay());
    }

    //设为首页
    function setHomePage (url){
	    if(document.all){
		    document.body.style.behavior='url(#default#homepage)';
		    document.body.setHomePage(url);
	    }else if(window.sidebar){ //兼容Firefox
		    if(window.netscape){
			    try{  
				    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
			    }catch (e){  
				    alert( "该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true" );  
          }
        } 
        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
        prefs.setCharPref('browser.startup.homepage',url);
	    }
    }

    //加入收藏夹
    function bookMarkSite (title, url){
	    if (document.all)
		    window.external.AddFavorite(url, title);
	    else if (window.sidebar)
		    window.sidebar.addPanel(title, url, "");
    }

    // 向指定框架中插入 script 或 link
    function appendLink(url, ifm, id) {
        var doc = ifm ? ifm.document : document;
        var isJs = url.toLowerCase().endsWith("js");
        if(!ifm) ifm = window;
        
        var link = doc.createElement(isJs ? "script" : "link");
        if(id) link.id = id;
        link.charset = 'utf-8';
        link.type = isJs ? "text/javascript" : "text/css";
        if(isJs) {
            link.src = url;
        }else {
            link.rel = "stylesheet";
            link.href = url;
        }
        
        doc.getElementsByTagName('head')[0].appendChild(link);
        link = null;
        delete link;
        doc = null;
    }
    
    // 向页面中载入 js 文件，载入成功后执行指定函数
    function requestJs() {//(url, id, fun, obj[, ...])
        var args = $A(arguments);
        var url = args.shift();
        var id = args.shift();
        var fun = args.shift();
        var object = args.shift();
        var script = document.createElement('script');
        script.charset = 'utf-8';
        script.src = url;
        script.id = id;
        script[document.all ? "onreadystatechange": "onload"] = function() {
            if (!document.all || script.readyState == 'loaded' || script.readyState == 'complete') {
                if(object)
                    return fun.apply(object, args);
                else
                    return fun(args);
            }
        }.bind(this);
        document.body.appendChild(script);
    }
    
    function setCookie(name, value, hours, path, domain, secure) { // 写 Cookie
        var str = escape(name) + "=" + escape(value);
        if (hours) {
            var nextTime = new Date();
            nextTime.setHours(nextTime.getHours() + hours);
            str += ";expires=" + nextTime.toGMTString();
        }
        if (path) str += ";path=" + path; // path 表示哪些路径下的文件有权限读取该 cookie
        if (domain) str += ";domain=" + domain;
        if (secure) str += ";secure";
        document.cookie = str;
    }
    function getCookie(name) { // 读 Cookie
        var pattern = "(^|;)\\s*" + escape(name) + "=([^;]+)";
        var m = document.cookie.match(pattern);
        if (m && m[2]) {
            return unescape(m[2]);
        } else {
            return null;
        }
    }
    function clearCookie(name, path, domain) { // 清除 Cookie
        this.setCookie(name, "", -1, path, domain);
    }
    
    // 操作Cookie
    function CookieHelper() {}
    CookieHelper.prototype.expires ='';
    CookieHelper.prototype.path    ='';
    CookieHelper.prototype.domain  ='';
    CookieHelper.prototype.secure  ='';
    //get Cookie value
    CookieHelper.prototype.getCookie = function(sCookieName){
        var sName=sCookieName+"=", ichSt, ichEnd;
        var sCookie=document.cookie;
        if ( sCookie.length && ( -1 != (ichSt = sCookie.indexOf(sName)) ) ){
            if (-1 == ( ichEnd = sCookie.indexOf(";",ichSt+sName.length)))
                ichEnd = sCookie.length;
            return unescape(sCookie.substring(ichSt+sName.length,ichEnd));
        }
        return null;
    }
    //set Cookie value
    CookieHelper.prototype.setCookie = function(sCookieName,sCookieValue,dCookieExpires){
        var argv = this.setCookie.arguments, argc = this.setCookie.arguments.length;
        var sExpDate = (argc > 2) ? "; expires="+argv[2].toGMTString() : "";
        var sPath = (argc > 3) ? "; path="+argv[3] : "";
        var sDomain = (argc > 4) ? "; domain="+argv[4] : "";
        var sSecure = (argc > 5) && argv[5] ? "; secure" : "";
        document.cookie = sCookieName + "=" + escape(sCookieValue,0) + sExpDate + sPath + sDomain + sSecure + ";";
    }
    
    //通用复制方法(操作剪贴板)
    function copyToClipboard(txt,msg) {
         if(window.clipboardData) {
                 window.clipboardData.clearData();
                 window.clipboardData.setData("Text", txt);
         } else if(navigator.userAgent.indexOf("Opera") != -1) {
              window.location = txt;
         } else if (window.netscape) {
              try {
                   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
              } catch (e) {
                   alert("您的浏览器未开启复制功能！\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");
                   return false;
              }
              var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
              if (!clip)
                   return;
              var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
              if (!trans)
                   return;
              trans.addDataFlavor('text/unicode');
              var str = new Object();
              var len = new Object();
              var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
              var copytext = txt;
              str.data = copytext;
              trans.setTransferData("text/unicode",str,copytext.length*2);
              var clipid = Components.interfaces.nsIClipboard;
              if (!clip)
                   return false;
              clip.setData(trans,null,clipid.kGlobalClipboard);
         }
         else
         {
            alert('您的浏览器不支持拷贝功能。');
            return false;
         }
         if(msg!=null&&msg!='')
         {
            alert(msg);
         }
         return true;
    }

    // 克隆对象
    function fnCloneObj(obj) {
	    var newObj = new Object();
	    for(elements in obj) {
		    newObj[elements] = obj[elements];
	    }
	    return newObj;
    }

    // 是否数字
    function isNumber(v) {
	    if(!v)return false;
	    return !isNaN(v);
    }

    // 取得窗口工作区大小
    function fnGetWindowSize() {
	    var size = {};
	    var _dEt = document.documentElement;
	    var _dBy = document.body;
	    if(typeof window.innerWidth=='number')size.width = window.innerWidth;
	    else{
		    if(_dEt&&_dEt.clientWidth)size.width = _dEt.clientWidth;
		    else{
			    if(_dBy&&_dBy.clientWidth)size.width = _dBy.clientWidth;
		    }
	    }
	    if(typeof window.innerHeight=='number')size.height = window.innerHeight;
	    else{
		    if(_dEt&&_dEt.clientHeight)size.height = _dEt.clientHeight;
		    else{
			    if(_dBy&&_dBy.clientHeight)size.height = _dBy.clientHeight;
		    }
	    }
	    if(!size.width||size.width<100)size.width = 100;
	    if(!size.height||size.height<100)size.height = 100;
	    size.w = size.width;
	    size.h = size.height;
	    return size;
    }

    // 实现 IIF
    function iif(bln, obj1, obj2) {
	    return bln ? obj1 : obj2;
    }

    // 获取经纬度字符串
    // mapX: 坐标
    // isPoint:  是否象素坐标
    function getFmtGis(coord, isPoint) {
        var gis = isPoint ? mapToGis(coord.x, coord.y) : coord;
        return "纬度:" + gisConvert(gis.lat()) + "N&nbsp;&nbsp;经度:" +  gisConvert(gis.lng()) + "E";
    }

    // 3D 地图坐标转 gis 坐标
    function mapToGis(point) {
        var xJ = 0.000002186986962562;
        var xW = 0.00000186134514748;
        var yJ = 0.000003641167826862;
        var yW = -0.000003102722061843;
        var x = point.x, y = point.y;

        return new GLatLng(x * xW + y * yW + 31.56848112478, x * xJ + y * yJ + 120.2215712512);
    }

    // gis 地图坐标转 3D 坐标
    function gisToMap(gis) {
        var xj = 228757.7023682;
        var xw = 268457.7988242;
        var xc = -35976415.02247;

        var yj = 137233.7282206;
        var yw = -161244.6728975;
        var yc = -11408204.83558;
        
        var w = gis.lat(), j = gis.lng();

        return new GPoint(Math.round(xj * j + xw * w + xc), Math.round(yj * j + yw * w + yc));
    }

    //经纬度数格式互换
    function gisConvert(data){
        var r;
        if(!isNaN(data)) {
            var d,f,m,t;
            d = Math.floor(data);
            t = (data - d) * 60;
            f = Math.floor(t);
            t = (t - f) * 60;
            m = t.toString();
            r = d + "°" + f + "'" + m.substring(0,m.indexOf(".") + 3) + "\"";
        }else {
            var a = data.replace(/[°'" ]+/g, "|").split("|");
            r = parseFloat(a[0]) + parseFloat(a[1]) / 60 + parseFloat(a[2]) / 3600;
        }
        return r;
    }
    
    //计算距离
    function mapDistance(pixel1, pixel2) {       
        return gisDistance(mapToGis(pixel1.x, pixel1.y), mapToGis(pixel2.x, pixel2.y))
    }

    function gisDistance(gis1, gis2) {
        var jL = 94826.59;
        var wL = 110749.12;
        if(!gis1) gis1 = new GLatLng(31.56848112478, 120.2215712512);
        
        var cJ = Math.abs(gis2.j - gis1.j) * jL;
        var cW = Math.abs(gis2.w - gis1.w) * wL;
        
        return Math.sqrt(cJ * cJ + cW * cW);
    }

    // 格式化 swf
    function getSwfStr(src, width, height, id) {
        var str = "<object id=\""+ (id || "") +"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0\" width=\"" + width + "\" height=\"" + height + "\">";
        str += "<param name=\"MENU\" value=\"FALSE\" />";
        str += "<param name=\"SRC\" value=\""+ src +"\" />";
        str += "<embed src=\""+ src +"\" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\"  width=\"" + width + "\" height=\"" + height + "\"></embed>";
        str += "</object>";
        return str;
    }
    
    function getMPlayerStr() {
        var str = "<object id=\"" + (id || "") + "\" height=0 width=0 classid=CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95></object>";
    }

    // 产生一个 guid 格式的字符串
    function createGuid() {
	    var guid= "";
	    for(var i=0;i < 32; i++) {
	      var n = Math.floor(Math.random()*16.0).toString(16);
	      guid += n;
	      if(i==7 || i==11 || i==15 || i==19)
		    guid += "-";
	    }
	    return guid;
    }

    // 向 document 中添加新命名空间
    function addNamespace(key, value) {
        var ns;
        try {
            ns = document.namespaces;
            NAMESPACES_LOADED = true;
        }catch(e) {
            if(!document.tryCount)
                document.tryCount = 0;
            else
                document.tryCount ++;
                
            if(document.tryCount < 100) {
                setTimeout("addNamespace('" + key + "','" + value + "')", 10);
                return;
            }
            return;
        }
        for(var i=0; i<ns.length; i++) {
            var name = ns(i).name;
            if(name.toLowerCase() == key.toLowerCase())
                return false;
        }
        document.namespaces.add(key, value);
    }

    function $findEvent() {
        var fun1 = $findEvent.caller;
        var fun = $findEvent.caller;
        while(fun != null) {
            var arg0 = fun.arguments[0];
            if(arg0 && (arg0.constructor == Event || arg0.constructor == MouseEvent))
                return arg0;
            fun = fun.caller;
            if(fun == fun1) return null;
        }
        return null;
    }
    
    //从“_key:value_;_key1:value1_;”这样的字符串中提取出 key 对应的 value
    function getValue(value,key) {
        var re;
        re = new RegExp("^" + key + ":([^\0]*?)$", "ig");
        if(value.match(re)) {
            return value.replace(re, "$1").replace(/_;/,"");
        }else {
            re = new RegExp("_" + key + ":([^\0]*?)_;", "ig");
            if(value.match(re)){
                re = new RegExp("^[^\0]*_" + key + ":([^\0]*?)_;[^\0]*$","ig");
                return value.replace(re, "$1");
            }
        }
        return "";
    }
    
    // 从 url 中提取值
    function getUrlValue(key, url) {
        url = url || location.search;
        var re = new RegExp(key + "[ ]*=[ ]*([^&]*)");
        var m;
        if((m = url.match(re)) && m.length > 1)
            return m[1];
        return "";
    }
    
    //每十秒做一次垃圾回收.IE可控制回收,FF过几十秒自动回收一次,不用调度
    if(document.all) {
        window.setInterval(CollectGarbage, 10000);
    }
    
    if(isIE)
        addNamespace("v", "urn:schemas-microsoft-com:vml");

    LIB_LOADED = true;
}