﻿/*
*
*date:2010-05-29
*author:xiaoxu
*email:y.j.alvin@gmail.com
*
*/

//js library,for operating events,cookies etc.
var _xuJsLibrary={
    //functions for add or remove event
    _eventHandle:{       
        addEvent:function(oTarget,eventType,fnHandle){
            if(oTarget.attachEvent)
                oTarget.attachEvent("on"+eventType,fnHandle);
            else if(oTarget.addEventListener)
                oTarget.addEventListener(eventType,fnHandle,false);
            else
                oTarget["on"+eventType]=fnHandle;
        },
        removeEvent:function(oTarget,eventType,fnHandle){
            if(oTarget.detachEvent)
                oTarget.detachEvent("on"+eventType,fnHandle);
            else if(oTarget.removeEventListener)
                oTarget.removeEventListener(eventType,fnHandle,false);
            else
                oTarget["on"+eventType]=null;
        }
    },
    //functions for set ,get or remove cookies
    _cookieHandle:{
        getCookie:function(n){  //获取制定名字的cookie值            
            var re=new RegExp(n+'=([^;]*);?','gi'); 
            var r=re.exec(document.cookie)||[]; 
            //return r.length;
            return unescape(r.length>1?r[1]:null); 
        },
        setCookie:function(n,v,e,p,d,s){    //设置cookie，n为名称，v为值,e为有效期,p为路径,d为domain,s为security
            var t=new Date();
            if(e)
                t.setTime(t.getTime()+(e*3600*1000)); //设置有效期，以小时为单位
            document.cookie=n+"="+escape(v)+(!e?"":";expires="+t.toGMTString())+(!p?"":";path="+p)+(!d?"":";domain="+d)+(!s?"":";secure");
        },
        removeCookie:function(n,p,d){
            document.cookie=n+"="+(!p?"":";path="+p)+(!d?"":";domain="+d)+";expires=Fri, 02-Jan-1970 00:00:00 GMT";
        }
    },
    //extand functions
    _extendFn:{
        lTrim:function(str){
            return str.replace(/(^\s*)/g,'');
        },
        rTrim:function(str){
            return str.replace(/(\s*$)/g,'');
        },
        trim:function(str){
            return str.replace(/(^\s*)|(\s*$)/g,'');
        },
        //去除数组中的重复值
        uniqueArray:function(arr){
            //不是数组时直接返回
            if(!(arr instanceof Array))
                return arr;
                
            var data=arr||[];
            var temp={};
            //把数组值当作下标，去除重复
            for(var i=0;i<data.length;i++)
                temp[data[i]]=true;
            
            data.length=0;
            for(var i in temp)
                data.push(i);
            return data;
        },
        //全选或取消全选
        checkAll:function(n){   //n 按名字取对象，sTarget 参考对象
            var objs=document.getElementsByName(n);
            for(var i=0;i<objs.length;i++)
                objs[i].checked=!objs[i].checked;
        },
        addFavorite:function(url,title){ //加入收藏夹
            try
            {
                window.external.addFavorite(url,title);     //ie
            }
            catch(e)
            {
                try
                {
                    window.sidebar.addPanel(title,url,"");  //firefox
                }
                catch(e)
                {
                    alert("加入收藏夹失败！\n请使用组合键Ctrl+D添加");  //operate
                }
            }
        },
        setAsHomePage:function(url,obj){    //设为首页
            try
            {
                //ie
                obj.style.behavior="url(#default#homepage)";
                obj.setHomePage(url);
            }
            catch(e)
            {
                if(window.netscape)
                {
                    try
                    {
                        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPContact");
                    }
                    catch(e)
                    {
                        alert("操作被拒绝！\n请在地址栏中输入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',location.href);
                }
            }
        },
        resizeImage:function(img,w,h){  //图片自适应大小
            if(!img) return false;
            
            //去除现有属性
            img.removeAttribute("width");
            img.removeAttribute("height");
            
            var temp;
            if(window.ActiveXObject)
            {
                temp=new Image();
                temp.pic=img.pic;
            }
            else
                temp=img;
            
            if(temp&&temp.width&&temp.height&&w)
            {
                if(!h) h=w;
                if(temp.width>w||temp.height>h)
                {
                    var scale=temp.width/temp.height;
                    var fit=scale>=w/h;
                    if(window.ActiveXObject)
                        img=img.style;
                    img[fit?'width':'height']=fit?w:h;
                    //ie6
                    if(window.ActiveXObject)
                        img[fit?'height':'width']=(fit?w:h)*(fit?1/scale:scale);
                }
            }
        },
        xmlHttpInit:function(fn){
            var objXmlHttp;
            //IE
            if(navigator.userAgent.indexOf("MSIE")>-1)
            {
                var temp="Msxml2.XMLHTTP";
                if(navigator.appVersion.indexOf("MSIE 5.5")>-1)
                    temp="Microsoft.XMLHTTP";
                try
                {
                    objXmlHttp=new ActiveXObject(temp);
                    objXmlHttp.onreadystatechange=fn;
                    return objXmlHttp;
                }
                catch(e)
                {
                    alert("您的浏览器不支持xmlhttp");
                    return;
                }
            }
            //Firefox
            if(navigator.userAgent.indexOf("Mozilla")>-1)
            {
                objXmlHttp=new XMLHttpRequest();
                objXmlHttp.onload=fn;
                objXmlHttp.onerror=fn;
                return objXmlHttp;
            }
            //Opera
            if(navigator.userAgent.indexOf("Opera")>-1)
            {
                alert("不支持Opera浏览器！");
                return;
            }
        },
        getElementCoordinate:function(elem){
            //获得页面元素的坐标位置
            var ret=[0,0]; //[x,y]
            
            //迭代元素到顶,依次增加x,y的值
            for(var e = elem;e ;e = e.offsetParent)
            {
                ret[0] += e.offsetLeft;
                ret[1] += e.offsetTop;
            }
            
            //减去滚动条的位置
            for(e = elem.parentNode;e && e != document.body; e = e.parentNode)
            {
                if(e.scrollLeft)
                    ret[0] -= e.scrollLeft;
                if(e.scrollTop)
                    ret[1] -= e.scrollTop;
            }
            
            return ret;
        },
        getQueryStringValue:function(fieldName){
            //获得url参数值
            var urlStr=document.location.search;
            if(urlStr!=null)
            {
                var indexStr=fieldName+"=";
                var index=urlStr.indexOf(indexStr);
                if(index!=-1)
                {
                    var tempUrl=urlStr.substring(index+indexStr.length);
                    var endIndex=tempUrl.indexOf("&");
                    if(endIndex==-1)
                        return tempUrl;
                    else
                        return tempUrl.substring(0,endIndex);
                }
                else
                    return "";
            }
            else
                return "";
        },
        browerDetection:function(){
            //检测当前浏览器类型及版本
            var ret={};
            var ua=navigator.userAgent.toLowerCase();
            
            var s="";
            (s = ua.match(/msie ([\d.]+)/)) ? ret.ie=s[1] :
            (s = ua.match(/firefox\/([\d.]+)/)) ? ret.firefox=s[1] :
            (s = ua.match(/chrome\/([\d.]+)/)) ? ret.chrome=s[1] :
            (s = ua.match(/opera.([\d.]+)/)) ? ret.opera=s[1] :
            (s = ua.match(/version\/([\d.]+).*safari/)) ? ret.safari=s[1] : 0;
            
            return ret;
        }
    },
    //functions for verify inputs
    _verifyFn:{
        runRegExp:function(pa,str){
            /*
            "^[a-zA-Z]{1}([a-zA-Z0-9]|[_]){2,15}$" 字母开头，数字，下划线，3－16位
            "^[a-zA-z]+:\/\/(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$"   url
            "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$" email
            "^[u4E00-u9FA5]+$"  中文
            */
            var re=new RegExp(pa,"g");
            if(re.test(str))
                return true;
            return false;
        }
    }
};
