﻿//脚本库
//黄起程
//2008-10-15
//最后修改 2009-5-8 

//对象扩展
Object.extendFn = function(target, sourceArray){
    for (var property in sourceArray)
    {
        try
        {
            switch(property.toString() )
            {
                case "fromElement":
                case "toElement":
                case "x":
                case "y":
                case "offsetX":
                case "offsetY":
                case "srcElement":
                case "returnValue":
                    continue;
                    break;
                default:
                    target[property] = sourceArray[property];
                    break;
            }
        }
        catch( exx )
        {}
    }
    return target;
}

//扩展String
Object.extendFn( String.prototype,{
    trim : function(){//清除左右端空格        
        return this.replace(/(^\s*)|(\s*$)/g, "");
    },
    ltrim : function(){//清除左端空格        
        return this.replace(/(^\s*)/g, "");
    },
    rtrim : function(){//清除右端空格        
        return this.replace(/(\s*$)/g, "");
    },
    clearHTML : function(){//清除html标签        
        return this.replace(/<[^>]*>/g, ""); 
    },
    lower : function(){//转为小写        
        return this.toLowerCase();
    },
    upper : function(){//转为大写
        return this.toUpperCase();
    },
    reallength : function(){//实际长度每个中文占两位
        return this.replace(/[^\u4e00-\u9fa5\uf900-\ufa2d]/,"**").length;
    },
    isChn : function(){//是否全为中文
        if(/^([\u4e00-\u9fa5\uf900-\ufa2d])*$/.test(this))   
            return true;   
        else   
            return false;
    },
    hasChn : function(){//是否包含中文
        if( /[\u4e00-\u9fa5\uf900-\ufa2d]/.test(this))   
            return true;   
        else   
            return false;
    },
    dbc2sbc : function(){//全角转半角
        var result = '',code='';
        for(var i=0;i<this.length;i++)
        {   
            code = this.charCodeAt(i);//获取当前字符的unicode编码   
            if(code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
                result += String.fromCharCode(this.charCodeAt(i) - 65248);//把全角字符的unicode编码转换为对应半角字符的unicode码
            else if(code == 12288)//空格
                result += String.fromCharCode(this.charCodeAt(i) - 12288 + 32);
            else 
                result += this.charAt(i);
        }
        return result;
    },
    format : function(){//参数格式化，如 "abc{0}efg{1}ijk".format("d","h") -> "abcdefghijk"        
        var args = arguments;
        return this.replace(/\{(\d+)\}/g,function(m,i){
            return args[i];
        });
    },
    append : function( str,before){
        //向当前字符串追加字符串,如:
        //"abc".append( "def" ) -> "abcdef";
        //"abc".append( "def",true ) -> "defabc";
        if( before!= null && before )
            return str.toString() + this;
        return this + str.toString();
    },
    appendFormat : function(){//串追参数格式化字符串，如:"abc".appendFormat("defg{0}ijk","h") -> "abcdefghijk"
        var fstr = arguments[0];
        var arr = $$.array( arguments );
        var args = arr.select( function( item,index ){
            return index != 0;
        });
        fstr = fstr.replace(/\{(\d+)\}/g,function(m,i){
            return args[i];
        });
        return this + fstr;
    },
    startWith : function(str){//是否以指定字符起始
        if( str == null || str == "" || this.length == 0 || str.length > this.length)
            return false;
        if(this.substr(0,str.length)==str)
            return true;
        else
            return false;
        return true;
    },
    endWith : function(str){//是否以指定字符结束
        if(str == null|| str == "" || this.length==0 || str.length > this.length)
            return false;
        if(this.substring(this.length-str.length)==str)
            return true;
        else
            return false;
        return true;
    },
    isNOrE : function(){//空对象或长度为0
        return (this == null) || (this.length == 0)
    },
    isN : function(){//是否数字
        return checkFn.isN(this);
    },
    isNN : function(){//是否正整数
        return checkFn.isNN( this );
    },    
    is_NN : function(){//是否负整数
        return checkFn.is_NN( this );
    },    
    isUserName : function(){//是否用户名格式
        return checkFn.isUserName( this );
    },
    isEmail : function(){//是否邮箱
        return checkFn.isEmail(this);
    },    
    isMobile : function(){//是否手机号
        return checkFn.isMobile(this);
    },    
    isTel : function(){//是否固定电话
        return checkFn.isTel(this);
    },    
    isIDCard : function(){//是否身份证,非严格判断
       return checkFn.isIDCard(this);
    },
    toInt : function(){//转为Int
        try{return parseInt( this );}
        catch(e){return 0;}
    },
    toDate : function(){//字符串转为Date
        var DateStr = this;
        if( !checkFn.isLDate( DateStr ) && !checkFn.isSDate( DateStr ) )//两种都不满足
            return null;
        
        var converted = Date.parse(DateStr);        
        var myDate = new Date(converted);
        if (isNaN(myDate))   
        {
            if( checkFn.isSDate( DateStr ) )
            {
                //2008-01-01
                var arys = DateStr.split('-');
                myDate = new Date(arys[0],--arys[1],arys[2]);
            }
            else
            {
                //2008-01-01 00:00:00
                var partArray = DateStr.split(" ");
                var darray = partArray[0].split("-");
                var tarray = partArray[1].split(":");
                myDate = new Date(darray[0],--darray[1],darray[2],tarray[0],tarray[1],tarray[2]);
            }
        }   
        return myDate; 
    },
    getArray : function(spliter){//将字符串转为数组
        var a = [];
        if( spliter == null || spliter == "")
        {
            for( var i=0;i<this.length;i++)
                a.insert(this.charAt(i),i);
        }
        else
            a = this.split( spliter );
            
        a = $$.array( a );
        return a;
    },
    isDateTime : function(){//是否日期时间//2008-01-01 00:00:00
        return checkFn.isLDate( this )
    },
    isDate : function(){//是否短日期//2008-01-01
        return checkFn.isSDate( this );
    },
    isTime : function(){//是否时间//00:00:00
        return checkFn.isTime( this );
    },
    times : function(n){//重复当前字符串n次
        var result = '';
        for (var i = 0; i < n; i++) 
		    result += this;
        return result;
    },
    padl : function(c,len){//以c补左，如 "2".padl("0",5) -> 00002
        if( this.length >= len )
            return this;
        var n = len - this.length;
        return  c.toString().times( n ) + this;
    },
    padr : function(c,len){//以c补右，如 "2".padr("0",5) -> 20000
        if( this.length >= len )
            return this;
        var n = len - this.length;
        return  this + c.toString().times( n );
    },
    camelize: function(){ //去掉"-"字符，并将"-"后的第一个字符转换为大写
        var parts = this.getArray('-'), len = parts.length;
        if (len == 1) 
            return parts[0];
        var camelized = this.charAt(0) == '-' ? parts[0].charAt(0).upper() + parts[0].substring(1) : parts[0];
        for (var i = 1; i < len; i++)
          camelized += parts[i].charAt(0).upper() + parts[i].substring(1);
        return camelized;
    },
    capitalize: function(){ //第一个字符转换为大写
        return this.charAt(0).upper() + this.substring(1).lower();
    }
});


//扩展Date
Object.extendFn(Date.prototype,{
    datePart : function(){//获取日期部分
        return this.format("yyyy-MM-dd");
    },
    timePart : function(){//获取时间部分
        return this.format("HH:mm:ss");
    },
    isLeapYear : function(){//判断闰年
        return (0==this.getYear()%4&&((this.getYear()%100!=0)||(this.getYear()%400==0)));    
    },
    format : function(formatStr){//日期格式化,如：(new Date()).format("yyyy-MM-dd HH:mm:ss")
        var str = formatStr;    
        var Week = ['日','一','二','三','四','五','六'];
        str=str.replace(/yyyy|YYYY/,this.getFullYear());    
        str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));    
      
        str=str.replace(/MM/,(this.getMonth()+1) > 9 ?(this.getMonth()+1).toString():'0' + (this.getMonth()+1));    
        str=str.replace(/M/g,(this.getMonth()+1));    
       
        str=str.replace(/w|W/g,Week[this.getDay()]);    
       
        str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());    
        str=str.replace(/d|D/g,this.getDate());    
       
        str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' + this.getHours());    
        str=str.replace(/h|H/g,this.getHours());    
        str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0' + this.getMinutes());    
        str=str.replace(/m/g,this.getMinutes());    
       
        str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0' + this.getSeconds());    
        str=str.replace(/s|S/g,this.getSeconds());    
       
        return str;    
    },    
    daysDiff : function(targetDate){//天数差,如：//new Date() = 2008-10-21, (new Date()).daysDiff("2008-10-20") -> 1
        var thisDate = this.format("yyyy-MM-dd");        
        var thisMonth = thisDate.substring(5,thisDate.lastIndexOf ('-'));   
        var thisDay = thisDate.substring(thisDate.length,thisDate.lastIndexOf ('-')+1);   
        var thisYear = thisDate.substring(0,thisDate.indexOf ('-'));   
       
        var targetMonth = targetDate.substring(5,targetDate.lastIndexOf ('-'));   
        var targetDay = targetDate.substring(targetDate.length,targetDate.lastIndexOf ('-')+1);   
        var targetYear = targetDate.substring(0,targetDate.indexOf ('-'));   
       
        var cha=((Date.parse(thisMonth+'/'+thisDay+'/'+thisYear)- Date.parse(targetMonth+'/'+targetDay+'/'+targetYear))/86400000);    
        return Math.abs(cha);
    },    
    dateDiff : function(datePart, dtEnd) {//时间差
        //datePart : 比较的部分
        //dtEnd 比较的时间
        var dtStart = this;
        dtEnd = dtEnd.toDate();        
        switch (datePart.lower()) 
        {    
            case 's' ://秒
                return parseInt((dtEnd - dtStart) / 1000);   
            case 'n' ://分
                return parseInt((dtEnd - dtStart) / 60000);   
            case 'h' ://时
                return parseInt((dtEnd - dtStart) / 3600000);   
            case 'd' ://天
                return parseInt((dtEnd - dtStart) / 86400000);   
            case 'w' ://周
                return parseInt((dtEnd - dtStart) / (86400000 * 7));   
            case 'm' ://月
                return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);   
            case 'y' ://年
                return dtEnd.getFullYear() - dtStart.getFullYear();   
        }   
    },
    dateAdd : function(datePart, Number) {
        var dtTmp = this;  
        var date; 
        switch (datePart) 
        {    
            case 's' :
                date = new Date(Date.parse(dtTmp) + (1000 * Number));
                break;
            case 'mi' :
                date = new Date(Date.parse(dtTmp) + (60000 * Number));  
                break; 
            case 'h' :
                date = new Date(Date.parse(dtTmp) + (3600000 * Number)); 
                break;  
            case 'd' :
                date = new Date(Date.parse(dtTmp) + (86400000 * Number)); 
                break;  
            case 'w' :
                date = new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
                break;
            case 'mon' :
                date = new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());   
                break;
            case 'y' :
                date = new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());   
                break;
        }
        return date.format("yyyy-MM-dd HH:mm:ss");
    },
    dayOfYear : function(){//一年中的第几天
        //当前date   
        var now = this;          
        //每月多少日   
        var monthOfFullDay = new Array(31,28,31,30,31,30,31,31,30,31,30,31);          
        //当前日，在本年中第几日   
        var currentDayOfYear = 0;          
        //是否为润年，即能被4整除   
        var isFullYear = false;
        var currentDayOfWeekIsLastDay = false;
        var firstDayOfYearIsFirstDayOfWeek = false;
        //当前年份   
        var year = 0;   
        if(now.getYear()>=2000)   
            year = now.getYear();   
        else  
            year = now.getYear() + 1900;
        //当前月份   
        var month = now.getMonth();
        //当前日   
        var day = now.getDate();
        //当前星期几   
        var week = now.getDay();
        //为闰年，设isFullYear为true   
        if(year%4==0){   
            isFullYear = true;   
        }
        //循环计算天数   
        for(var i=0;i<monthOfFullDay.length;i++)
        {   
            //判断数组月份是否小于等于当前月份   
            if(i<month)
            {   
                //是闰年和2月份   
                if(isFullYear && i==1)   
                    currentDayOfYear = currentDayOfYear + 29;   
                else  
                    currentDayOfYear = currentDayOfYear + monthOfFullDay[i]; 
            }   
            if(i==month)   
                currentDayOfYear = currentDayOfYear + day;   
        }
        
        //设置本年1月1日   
        var firstDayOfYear = new Date();
        firstDayOfYear.setYear(year);   
        firstDayOfYear.setMonth(0);   
        firstDayOfYear.setDate(1);    
          
        if(firstDayOfYear.getDay()==0)
            firstDayOfYearIsFirstDayOfWeek = true;
          
        var weeksOfYear = currentDayOfYear;   
          
        //本星期是否为最后一日，否，则减去本兴起所有日   
        if(!currentDayOfWeekIsLastDay)
            weeksOfYear = weeksOfYear + firstDayOfYear.getDay();
          
        //是否第一个星期为第一日（即星期日），否，则减去本星期所有日   
        if(!firstDayOfYearIsFirstDayOfWeek)
            weeksOfYear = weeksOfYear + (7-week-1);
        
        return weeksOfYear;
    },
    weekOfYear : function(){//年的第几周
        var day = this.dayOfYear();
        return day/7; 
    },
    dayOfWeek : function(){//周的第几天
        return this.getDay();
    },
    dayOfWeekCn : function(){//星期，中文
        return ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"][this.getDay()];
    },
    dayOfWeekEn : function(){//星期，英文
        return ["SUNDAY","MONDAY","TURESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"][this.getDay()];
    }
});
//枚举函数
var enumFn = {
    each: function(func){//遍历每个成员
        var index = 0;
        try 
        {
            this._each(function(value){
                func(value, index++);
            });
        } 
        catch (e)
        {}
        return this;
    },
    all: function(func){//返回所有满足func条件的元素,array
        var result = true;
        this.each(function(value, index){
            result = result && !!(func || fn.kong)(value, index);
        });
        return result;
    },
    any: function(func){//是否有任意满足func条件的元素:bool
        var result = false;
        this.each(function(value, index){
            if (result = !!(func || fn.kong)(value, index))
                throw {};
        });
        return result;
    },
    collect: function(func){//检查每个元素是否满足func条件:array
        var results = [];
        this.each(function(value, index){
            results.push((func || fn.kong)(value, index));
        });
        return results;
    },
    detect: function(func){//查找符合func条件的最后一个元素
        var result;
        this.each(function(value, index){
            if (func(value, index))
            {
                result = value;
                return;
            }
        });
        return result;
    },
    findAll: function(func){//返回所有满足func条件的元素,array
        var results = [];
        this.each(function(value, index){
            if (func(value, index))
            {
                results.push(value);
                return;
            }
        });
        return results;
    },
    toArray: function(){
        return this.map();
    },
    include: function(obj){//是否包含obj对象
        var found = false;
        this.each(function(value){
            if (value == obj)
            {
                found = true;
                return;
            }
        });
        return found;
    },
    max: function(func){//最大值
        var result;
        this.each(function(value, index){
                value = (func || fn.kong)(value, index);
                if (result == undefined || value >= result)
                    result = value;
        });
        return result;
    },
    min: function(func){//最小值
        var result;
        this.each(function(value, index){
            value = (func || fn.kong)(value, index);
            if (result == undefined || value < result)
                result = value;
        });
        return result;
    }
}

Object.extendFn(enumFn, {
  map:  enumFn.collect,//检查每个元素是否满足func条件:array
  find: enumFn.detect,//查找符合func条件的最后一个元素
  select:  enumFn.findAll,//所有满足func条件的元素,array
  contain: enumFn.include,///是否包含obj对象
  arr:  enumFn.toArray
});

Object.extendFn(Array.prototype, enumFn);

//扩展Array
Object.extendFn(Array.prototype,{
    _each: function(func){//遍历每个成员
        for (var i = 0, length = this.length; i < length; i++)
            func(this[i]);
    },
    size : function(){//元素数量
        return this.length;
    },
    clear : function(){//清除所有元素
        this.length = 0;
        return this;
    },
    first : function(){//第一个元素
        if( this.length == 0 )
            return null;
        return this[0];
    },
    last : function(){//最后一个元素
        if( this.length == 0 )
            return null;
        return this[this.length - 1];
    },
    index: function(obj){//索引
        for (var i = 0, length = this.length; i < length; i++)
            if (this[i] == obj) 
                return i;
        return -1;
    },
    exclude: function(){//排除指定元素
        var values = fn.array(arguments);
        return this.select(function(value){
          return !values.include(value);
        });
    },
    clearNull: function(){//清除所有空值
        return this.select(function(value){
            return value != null;
        });
    },
    rnd : function( c ){//从数组中任意选择c个不重复元素
        var arr = this;
        var d = [];
        if( arr == null || arr.length == 0 || c <= 0 )
            return d;    
        arr = $$.array( arr );
        if( c >= arr.length )
            return arr;
        var index = [];
        var r;
        for( var i=0;i<c;i++)
        {
            while( r == null || index.include( r ) )
            {
                r = $$.rndInt(arr.length.toString().length,0,arr.length-1);
                r = parseInt( r.toString() );
            }
            index[i] = r;
        }
        
        index.sort();
        index.each( function(i){
            d[d.length] = arr[i];
        });
        return d;

    },
    insert : function(obj,index){//在指定索引位置插入对象
        if( index + 1 > this.length )
            index = this.length;
        
        var result1,result2,result;
        result = [];
        var ii = 0;
        result1 = this.select( function( item,i ){
            return i < index;
        });
        result2 = this.select( function( item,i ){
            return i >= index;
        });
        result1.each( function( item ){
            result[ii++] = item;
        });
        result[ii++] = obj;
        result2.each( function( item ){
            result[ii++] = item;
        });
        
        return result;
    }
});

var fn = {
    dload: function(func)
    {
        if (func != null && typeof func == 'function')
            window.onload = func;
    },
    kong: function(val)
    {//空函数，直接返回参数
        return val;
    },
    idObj: function(id)
    {//根据id查询对象,对象扩展domFn

        var obj = null;
        if (typeof id == 'string')
            obj = document.getElementById(id);
        else if (typeof id == 'object')
            obj = id;
        else
            obj = null;
        if (obj != null)
            obj = Object.extendFn(obj, domFn);
        return obj;
    },
    nameObj: function(name, target)
    {//根据name查询对象,对象扩展domFn
        if (typeof name == 'undefinded' || name == null)
            return new Array();
        if (target == null)
        {
            var array = document.getElementsByName(name);
            array = $$.array(array);
            array.each(function(item)
            {
                Object.extendFn(item, domFn);
            });
        }
        else
        {
            target = $$.idObj(target);
            var els = $$.tagObj("*", target);

            els = $$.array(els);
            var att;
            var array = els.select(function(m, i)
            {
                att = m.getAttribute("name");
                return att != null && att.lower() == name.lower();
            });
            array.each(function(item)
            {
                Object.extendFn(item, domFn);
            });
        }
        return array;
    },
    classObj: function(className, target)
    {//根据class查询对象,对象扩展domFn
        if (typeof className == 'undefinded' || className == null)
            return new Array();
        if (target == null)
        {
            var array = document.getElementsByClassName(className);
            array.each(function(item)
            {
                Object.extendFn(item, domFn);
            });
        }
        else
        {
            target = $$.idObj(target);
            var els = $$.tagObj("*", target);
            els = $$.array(els);
            var att;
            var array = els.select(function(m, i)
            {
                att = m.className;
                return att != null && att.lower() == className.lower();
            });

            array.each(function(item)
            {
                Object.extendFn(item, domFn);
            });
        }
        return array;
    },
    tagObj: function(tag, target)
    {//根据tag查询对象
        if (typeof tag == 'undefinded' || tag == null)
            return new Array();
        if (tag == "")
            tag = "*";
        if (target == null)
        {
            var objArr = document.getElementsByTagName(tag);
            objArr = $$.array(objArr);

            objArr.each(function(item)
            {
                Object.extendFn(item, domFn);
            });
        }
        else
        {
            target = $$.idObj(target);
            var objArr = target.getElementsByTagName(tag);
            objArr = $$.array(objArr);
            objArr.each(function(item)
            {
                Object.extendFn(item, domFn);
            });
        }
        return objArr;
    },
    ctrl13: function(func)
    {//ctrl + 回车 ，执行func
        if (event.ctrlKey && event.keyCode == 13)
        {
            if (func != null && typeof func == "function")
                func();
        }
    },
    enterTab: function(obj)
    {//回车后执行Tab
        obj = this.idObj(obj);
        if (obj == null)
            return false;
        obj.onkeydown = function()
        {
            if (event.keyCode == 13)
                event.keyCode = 9;
        }
    },
    array: function(input)
    {//将输入对象转为Array
        if (!input)
            return [];
        if (input.toArray)
            return input.toArray();
        else
        {
            var results = [];
            for (var i = 0, length = input.length; i < length; i++)
                results.push(input[i]);
            return results;
        }
    },
    activeObj: function()
    {//当前文档的活动对象
        var obj = null;
        if (browserFn.ie)
            obj = document.activeElement;
        else if (browserFn.firefox)
            obj = e ? e.explicitOriginalTarget : null;
        return obj;
    }
}

//DOM
var domFn = {
    string: function()
    {
        return this.outerHTML;
    },
    wh: function()
    {//获取宽高，即使隐藏也能获取
        var display = this.style ? this.style.display : "none";
        if (display != 'none' && display != null)
            return { width: this.offsetWidth, height: this.offsetHeight };

        var els = this.style;
        var originalVisibility = els.visibility;
        var originalPosition = els.position;
        var originalDisplay = els.display;
        els.visibility = 'hidden';
        els.position = 'absolute';
        els.display = 'block';
        var originalWidth = this.clientWidth;
        var originalHeight = this.clientHeight;
        els.display = originalDisplay;
        els.position = originalPosition;
        els.visibility = originalVisibility;
        return { width: originalWidth, height: originalHeight };
    },
    offsetPos: function()
    { //获取对象位置：top,left
        iPos_x = 0, iPos_y = 0;
        var el = this;
        while (el != null)
        {
            iPos_x += el["offsetLeft"]
            iPos_y += el["offsetTop"]
            el = el.offsetParent
        }
        var pos = {}
        pos.left = iPos_x;
        pos.top = iPos_y;
        return pos
    },
    setOpacity: function(value)
    {//设置透明度
        this.style.filter = "alpha(opacity={0})".format(parseFloat(value) * 100);
        this.style.opacity = (value == 1 || value === "") ? "" : (value < 0.00001) ? 0 : value;
        return this;
    },
    bottom: function()
    {//对象的底
        var pos = this.offsetPos();
        return pos.top + this.offsetHeight;
    },
    right: function()
    {//对象的右
        var pos = this.offsetPos();
        return pos.left + this.offsetWidth;
    },
    hide: function()
    {//隐藏
        this.css("display", "none");
        return this;
    },
    show: function(showtype)
    {//显示
        this.css("display", showtype == null ? "" : showtype);
        return this;
    },
    ishide: function()
    {
        return this.css("display").lower() == "none";
    },
    html: function(_html, append)
    {//读取或设置innerHTML,这里需要补充，在ie中table对象不能直接设置innerHTML
        switch (this.tag().upper())
        {
            case "TABLE":
            case "TR":
            case "TD":
            case "P":
                if (_html != null)
                {
                    var t = this;
                    var cs = $$.array(t.childNodes);
                    cs.each(function(c)
                    {
                        t.removeChild(c);
                    });

                    var o = $$.el("span");
                    o.innerHTML = _html;
                    t.appendChild(o);
                    return t;
                }
                else
                    return "";
                break;
            default:
                if (_html != null)
                {
                    if (append == null || !append)
                        this.innerHTML = _html;
                    else
                        this.innerHTML += _html;
                    return this;
                }
                return this.innerHTML;
                break;
        }

    },
    tag: function()
    {//读取标签
        return this.tagName;
    },
    val: function(_val)
    {//读取或设置值
        switch (this.tag().upper())
        {
            case "INPUT":
            case "SELECT":
                if (_val != null)
                {
                    this.value = _val;
                    return this;
                }
                return this.value;
                break;
            default:
                return "";
                break;
        }
    },
    att: function(_att, _val)
    {//读取或设置属性
        if (_val != null)
        {
            this.setAttribute(_att, _val)
            return this;
        }
        return this.getAttribute(_att) == null ? "" : this.getAttribute(_att);
    },
    pre: function()
    {//前一个对象
        if (this.previousSibling == null)
            return null;
        var p = this.previousSibling;
        while (p != null && p.tagName == null)
        {
            p = p.previousSibling;
        }
        return $$.idObj(p);
    },
    next: function()
    {//后一个对象
        if (this.nextSibling == null)
            return null;
        var p = this.nextSibling;
        while (p != null && p.tagName == null)
        {
            p = p.nextSibling;
        }
        return $$.idObj(p);
    },
    last: function(tag)
    {
        var objs = $$.tagObj(tag == null ? "*" : tag, this);
        if (objs.length == 0)
            return null;
        var obj;
        if (tag == null)
        {
            obj = objs[objs.length - 1];
            while (obj.tagName == null)
            {
                if (obj.previousSibling == null)
                {
                    obj == null;
                    break;
                }
                obj = obj.previousSibling;
            }
        }
        else
        {
            obj = objs[objs.length - 1];
            while (obj.tagName == null || obj.tagName != tag)
            {
                if (obj.previousSibling == null)
                {
                    obj == null;
                    break;
                }
                obj = obj.previousSibling;
            }
        }
        return obj == null ? null : $$.idObj(obj);
    },
    clearChild: function()
    {//清除内部
        if (this.innerHTML)
            this.innerHTML = "";
        return this;
    },
    append: function(child)
    {//追加
        if (child == null)
            return this;
        this.appendChild(child);
        return this;
    },
    prepend: function(node)
    {
        if (typeof node == 'string')
            node = $$.htmlObj(node);
        this.parentNode.insertBefore(node, this);
    },
    pendnext: function(node)
    {
        if (typeof node == 'string')
            node = $$.htmlObj(node);
        this.parentNode.insertBefore(node, this.nextSibling);
    },
    remove: function(child)
    {//移除指定子元素
        if (child == null)
            return this;
        this.removeChild(child);
        return this;
    },
    parent: function()
    {//父元素
        return $$.idObj(this.parentNode);
    },
    childs: function()
    {//子元素
        var cArray = this.childNodes;
        cArray = $$.array(cArray);
        return cArray;
    },
    cls: function(_class, append)
    {//读取或设置class,append:是否追加
        if (_class == null)
            return this.className;

        if (append == null || !append)//替换
        {
            this.className = _class;
        }
        else//追加
        {
            var classArray = this.className.split(" ");
            if (!this.hasClass(_class))
                this.className += (" " + _class);
        }
        return this;
    },
    hasClass: function(_class)
    {//是否包含指定的样式表
        if (_class == null)
            return false;

        var classArray = this.className.split(" ");
        if (!classArray.include(_class))
            this.className += " " + _class;
        return this;
    },
    cssTxt: function(_cssTxt, append)
    {//读取或设置style
        if (_cssTxt != null)
        {
            if (append == null || !append)
                this.style.cssText = _cssTxt;
            else
                this.style.cssText = this.style.cssText.toString() + ";" + _cssTxt;
            return this;
        }
        if (!this.style)
            return "";
        return this.style.cssText;
    },
    css: function(property, _val)
    {//读取或设置指定样式
        var element = this, elementStyle = element.style;
        if (_val != null)//设置样式
        {
            if (property == 'opacity')
                element.setOpacity(styles[property])
            else
            {
                var p;
                if (property == 'float' || property == 'cssFloat')
                    p = elementStyle.styleFloat === undefined ? 'cssFloat' : 'styleFloat';
                else
                    p = property.camelize();
                elementStyle[p] = _val;
            }
            return element;
        }
        else//读取样式
        {
            property = property == 'float' ? 'cssFloat' : property.camelize();
            var value = element.style[property];
            if (value == null)
            {
                var _css = document.defaultView.getComputedStyle(element, null);
                value = _css ? _css[property] : null;
            }
            if (property == 'opacity')
                return value ? parseFloat(value) : 1.0;

            return value == 'auto' ? null : value;
        }
    },
    block: function(doblock, blockText)
    {//覆盖阻断，cover效果
        if (blockText == null)
            blockText = "";
        if (doblock == null || doblock)
            htmlFn.block(this, blockText, 80, false);
        else
            htmlFn.blockend(this);
    },
    fill: function(url)
    {//用指定的url页面的html来填充当前对象的内部html
        $$.update(this, url);
    }
}

var posFn = {
    offsetPos : function(id){ //获取对象位置：Top,Left
        iPos_x = 0,iPos_y = 0;
        var el;
        if( typeof id == 'string')
            el = fn.idObj( id );
        else
            el = id;    
        while (el!=null)  
        {
            iPos_x += el["offsetLeft"] 
            iPos_y += el["offsetTop"] 
            el = el.offsetParent
        } 
        var pos = {}
        pos.left = iPos_x;
        pos.top = iPos_y;
        return pos
    }
}

var browserFn = {
    ie : navigator.userAgent.lower().indexOf('msie') > -1,
    ie6 : navigator.userAgent.lower().indexOf('msie 7') > -1 ? false : navigator.userAgent.lower().indexOf('msie 6') > -1,
    ie7 : navigator.userAgent.lower().indexOf('msie 7') > -1,
    maxthon : navigator.userAgent.lower().indexOf('maxthon') > -1,
    firefox : navigator.userAgent.lower().indexOf('firefox') > -1,
    google : navigator.userAgent.lower().indexOf('chrome') > -1,//google浏览器
    opera : !!window.opera,
    webKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
    version : function(){
        var p = navigator.userAgent;
        var pArray
        var find = false;
        var v = 0;
        if( this.ie )
        {
            pArray = p.getArray(";");
            pArray.each( function( item ){
                if( !find && item.lower().trim().indexOf('msie')>-1)
                {
                    find = true;
                    var arr = item.trim().getArray(" ");
                    v = parseInt(arr[1]);
                }
            });
        }
        else if( this.firefox )
        {
            pArray = p.getArray(" ");
            pArray.each( function( item ){
                if( !find && item.lower().trim().indexOf('firefox')>-1)
                {
                    find = true;
                    var arr = item.trim().getArray("/");
                    v = parseInt(arr[1]);
                }
            });
        }
        else 
            v = 0;
        return v;
    },
    avail : function(){//浏览器宽高
        var winWidth = 0, winHeight = 0;
        if (window.innerWidth)//for ie
        {
           winWidth = window.innerWidth;
           winHeight = window.innerHeight;
        }
        else ((document.body) && (document.body.clientWidth))
        {
           winWidth = document.body.clientWidth;
           winHeight = document.body.clientHeight;
        }

        //通过深入Document内部对body进行检测，获取窗口大小
        if (document.documentElement && document.documentElement.clientWidth)
        {
           winWidth = document.documentElement.clientWidth;
           winHeight = document.documentElement.clientHeight;
        }
        var _avail = {};
        _avail.width = winWidth;
        _avail.height = winHeight;
        return _avail;
    },
    docAvail : function(){//页面文档宽高
        var avail = {};
        avail.width = document.body.scrollWidth;//文档内容(页面)宽度
        avail.height = document.body.scrollHeight;//文档内容(页面)高度
        return avail;
    },
    center : function(obj){//浏览器中心点，指供obj时，返回能够使obj居中的top和left
        var avail = this.avail();
        var loc = {};
        if( typeof obj == 'undefined' || obj == null )
        {
            loc.left = avail.width/2 ;
            loc.top = avail.height/2;
        }
        else if( typeof obj == 'object' )
        {        
            loc.left = ( avail.width - el.offsetWidth )/2 ;
            loc.top = ( avail.height - el.offsetHeight )/2;
        }
        else if( typeof obj == 'string' )
        {
            obj = fn.idObj( obj );
            if( obj == null )
            {
                loc.left = avail.width/2 ;
                loc.top = avail.height/2;
            }
            else
            {
                loc.left = ( avail.width - el.offsetWidth )/2 ;
                loc.top = ( avail.height - el.offsetHeight )/2;
            }
        }
        return loc;
    },
    closeWindow : function(){
        window.open('','_parent','');
	    window.close();
    }
}

var htmlFn = {
    el: function(tag)
    {
        return document.createElement(tag);
    },
    addel: function(obj, target)
    {
        if (target == null)
            document.body.appendChild(obj);
        else
            target.appendChild(obj);
        return fn.idObj(obj);
    },
    html: function(id, html, append)
    {
        var obj = fn.idObj(id);
        if (html == null)
        {
            if (obj == null)
                return "";
            return obj.innerHTML;
        }
        else
        {
            if (obj == null)
                return;
            if (append == null || !append)
                obj.innerHTML = html;
            else
                obj.innerHTML += html;
        }
    },
    maxindex: function()
    {
        var els = $$.tagObj("*");
        var max = 0;
        var z;
        els.each(function(el)
        {
            if (el.style && el.style.zIndex)
            {
                z = el.css("zIndex"); 
                if (z != null)
                {
                    if( typeof z == "string" )
                        z = z.toInt();
                    if (z > max)
                        max = z;
                }
            }
        });
        return max;
    },
    block: function(target, blockText, opacity, showStep)
    {
        if (opacity == null)
            opacity = 65;
        if (opacity == 100)
            opacity = 99;

        var targetObj = fn.idObj(target);
        if (targetObj == null)
            return false;
        var blockObjId = targetObj.id + "_block";
        var blockObj = fn.idObj(blockObjId);

        if (blockObj == null)
        {
            blockObj = this.el("DIV");
            blockObj.id = blockObjId;
            blockObj = this.addel(blockObj);

            blockObj.cssTxt("position:absolute; display:none;top:0px;left:0px;background-color:Green;filter:alpha(opacity={0});opacity:0.{0}".format(opacity));
            blockObj.html('  <iframe style="background-color:#ccc;Z-INDEX: -1; FILTER: progid: DXImageTransform.Microsoft.Alpha(style=0,opacity=0); LEFT: 0px; VISIBILITY: inherit; WIDTH: 100%! important; POSITION: absolute; TOP: 0px; HEIGHT: 100%!important" src="" frameBorder="0" scrolling="no"></iframe>\
                                    <table border="0" width="100%" height="100%" style="font-size:12px;">\
                                        <tr>\
                                            <td align="center" style="height:70%" valign="middle">\
                                                <div id="' + targetObj.id + '_blockText">' + blockText + '</div>\
                                            </td>\
                                        </tr>\
                                        <tr>\
                                            <td align="center" valign="middle">\
                                            </td>\
                                        </tr>\
                                    </table>');
        }
        else
        {
            $$.idObj(targetObj.id + "_blockText").html(blockText)
        }

        var w = targetObj.offsetWidth;
        var h = targetObj.offsetHeight;
        var zindex = targetObj.style.zIndex;
        zindex = zindex.toString().trim() == "" ? $$.maxindex() : zindex;
        blockObj.style.display = "none";
        var pos = targetObj.offsetPos();
        blockObj.style.left = pos.left + "px";
        blockObj.style.top = pos.top + "px";
        blockObj.style.width = w + "px";
        blockObj.style.height = h + "px";
        blockObj.style.zIndex = (zindex + 1).toString();
        if ($$.ie)
            blockObj.firstChild.style.height = h + "px";
        else if ($$.firefox)
            blockObj.firstChild.nextSibling.style.height = h + "px";
        blockObj.style.display = "";
        if (showStep != null && showStep)
        {
            var tmp = 0;

            blockObj.style.filter = "alpha(opacity=" + tmp + ")";
            blockObj.style.opacity = "0." + tmp;

            var showStopTimer = timerFn.tick(function()
            {
                if (tmp < opacity)
                {
                    tmp = tmp + 8;
                    cssFn.trans(blockObj, tmp);
                }
                else
                    timerFn.tickend(showStopTimer);

            }, 0.001);
        }
        return blockObj;
    },
    blockend: function(target)
    {
        var targetObj = fn.idObj(target);
        if (targetObj == null)
            return false;
        var blockObjId = targetObj.id + "_block";

        var blockObj = fn.idObj(blockObjId);
        if (blockObj == null)
            return false;
        blockObj.hide();
    },
    preload: function(imgs, callback)
    {
        var img;
        for (var i = 0; i < imgs.length; i++)
        {
            img = new Image();
            img.index = i;
            img.onerror = img.onload = function()
            {
                var ii = parseInt(this.index);
                if ((ii + 1) == imgs.length)
                {
                    if (callback != null)
                        callback();
                }
            }
            img.src = imgs[i].src;
        }
    }
}

var cssFn = {
    trans : function ( target,opacity ){
        var targetObj = fn.idObj( target );
        if( targetObj == null )
            return;
        if( opacity == null || mathFn.toInt( opacity ) < 0  || mathFn.toInt( opacity ) > 100 )
            opacity = 99;
        
        targetObj.style.filter = "alpha(opacity="+ opacity +")"; 
        targetObj.style.opacity = "0." + opacity; 
    },    
    css : function(id,key,value){
        var obj = fn.idObj( id );
//        if( obj == null)
//            return;
        
    },
    csstxt : function(id,txt){
        var obj = fn.idObj( id );
        if( obj == null || txt== null)
            return;
        obj.style.cssText = txt;
    }
}
var checkFn = {
    //数字
    isN : function(str){
        if( str == null )
            return false;
        str = str.trim();
        if(/^(\-|\+)?(\d+)*$/.test(str))
            return true;
        return false;
    },
    //正整数
    isNN : function( str ){
        if( str == null )
            return false;
        str = str.trim();
        if(/^(((\+)?[1-9]+(\d*))|(([1-9])+(\d*)))$/.test(str)) // 例: +10 或 10
            return true;
        return false;
    },
    //负整数
    is_NN : function( str ){
         if( str == null )
            return false;
        str = str.trim();
        if( /^(\-){1}(\d+)*$/.test(str) )
            return true;
        return false;
    },
    //验证用户名
    isUserName : function( str ){
        if( str == null )
            return false;
        str = str.trim();
        //非数字开头，字母数字下划线，6~18位
        if( /^[A-Za-z_]{1}[A-Za-z0-9_]{5,17}$/.test( str ) )
            return true;
        return false;
    },
    //邮箱
    isEmail : function( str ){
        if( str == null )
            return false;
        str = str.trim();
        var reg = /^([a-zA-Z0-9_-])+(\.*)([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        return reg.test(str);
    },
    //手机号
    isMobile : function( str ){
        if( str == null )
            return false;
        str = str.trim();
        if( /^1[0-9]{10}$/.test(str))
            return true;
        return false
    },
    //固定电话
    isTel : function( str ){
        if( str == null )
            return false;
        str = str.trim();
        //3~4位区号-7~8位电话号码
        if( /^(\d{3,4})-(\d{7,8})/.test( str ) )
            return true;
        return false;
    },
    //身份证,非严格判断
    isIDCard : function(str){
        if( /^(\d{18}|\d{15}|\d{14}[A-Za-z]{1})$/.test(str) )
            return true;
        return false;
    },
    //日期+时间
    isLDate : function(str){
        if( /^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[0-9])|([1][0-9])|([2][0-4]))\:([0-5]?[0-9])((\s)|(\:([0-5]?[0-9])))))?$/.test( str.trim() ) )
            return true;
        return false;
    },
    //日期
    isSDate : function(str){
        if( /^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))$/.test( str.trim() ) )
            return true;
        return false;
    },
    //时间,有点失灵
    isTime : function(str){
        if( /^(\s(((0?[0-9])|([1][0-9])|([2][0-4]))\:([0-5]?[0-9])((\s)|(\:([0-5]?[0-9])))))?$/.test( str.trim() ) );
            return true;
        return false;
    }
}

//Url
var urlFn = {
    encode : function( str ){ 
        if( str == null )
            str = document.location.toString();
        return encodeURI( str )
    },
    decode : function( str ){
        if( str == null )
            str = document.location.toString();
        return decodeURI( str )
    },
    url : document.location,
    host : document.location.hostname,
    port : document.location.port,
    path : document.location.pathname,
    root : function(){
        return this.url.protocol + "//" + this.url.hostname + (this.url.port == "80" ? "" : ":"+this.url.port) + "/";
    },
    page : function(){
        var index = this.path.lastIndexOf("/");
        if( index < 0 )
            return this.path;
        return this.path.substr( index + 1 );
    },
    pageNoQ : function(){
        var u = this.url.toString();
        
        for( var i=0;i<u.length;i++){
            if( u.charAt( i ) == '?' )
            {
                return u.substr(0,i);
            }
        }
        return u;
    },
    ext : function(){
        var p = this.page();
        if( p == "" )
            return "";
        var index = p.lastIndexOf(".");
        if( index < 0 )
            return "";
        return p.substr( index + 1 );
    },
    noq : function(key){
        key = key.lower();
        var queryStr = this.qstr;
        if( queryStr.length > 0 )
            queryStr = queryStr.substr(1);
        
        var kvArray = queryStr.split("&");
        var itemArray;
        var newQ = "?";
        var find = false;
        for( var i=0;i<kvArray.length;i++)
        {
            itemArray = kvArray[i].split("=");
                        
            if( itemArray[0].toLowerCase() != key )
            {
                newQ += newQ == "?" ? "" : "&";
                newQ += "{0}={1}".format(itemArray[0],itemArray[1]);
            }
        }        
        var noq = this.pageNoQ();
        return noq + newQ;
    },    
    qstr : document.location.search,
    q : function(key,v){
        if( v == null )
        {
            key = key.lower();
            var queryStr = this.qstr;
            if( queryStr.length > 0 )
                queryStr = queryStr.substr(1);
            
            var kvArray = queryStr.split("&");
            var itemArray;
            for( var i=0;i<kvArray.length;i++)
            {
                itemArray = kvArray[i].split("=");
                //find
                if( itemArray[0].toLowerCase() == key )
                {
                    if( itemArray.length == 2 )
                        return itemArray[1];
                    return "";
                }
            }
            //no find
            return "";
        }
        else
        {
            key = key.lower();
            var queryStr = this.qstr;
            if( queryStr.length > 0 )
                queryStr = queryStr.substr(1);
            
            var kvArray = queryStr.split("&");
            var itemArray;
            var newQ = "?";
            var find = false;
            for( var i=0;i<kvArray.length;i++)
            {
                itemArray = kvArray[i].split("=");
                newQ += newQ == "?" ? "" : "&";
                //find
                if( itemArray[0].toLowerCase() == key )
                {
                    find = true;
                    newQ += "{0}={1}".format(itemArray[0],v);
                }
                else
                    newQ += "{0}={1}".format(itemArray[0],itemArray[1]);
            }
            if( !find )
            {
                newQ += newQ == "?" ? "" : "&";
                newQ += "{0}={1}".format(key,v);
            }
            var noq = this.pageNoQ();
            return noq + newQ;
        }
    },
    keys : function(){
        var queryStr = this.qstr;
        if( queryStr.length > 0 )
            queryStr = queryStr.substr(1);
        
        var kvArray = queryStr.split("&");
        var itemArray,keyArray;
        keyArray = [];
        for( var i=0;i<kvArray.length;i++)
        {
            itemArray = kvArray[i].split("=");
            keyArray[i] = itemArray[0];
        }
        return keyArray;
    },
    reload : function(){
        document.location.reload();
    },
    direct : function( str ){
        document.location.href = str;
    }
}

//Cookie
var cookieFn = {
    cookies : function(name, value, time, path, domain){
        if( value != null )
        {
            var expires = "";
            if (time) 
            {
                var date = new Date();
                date.setTime(date.getTime() + time * 1000);
                expires = "; expires=" + date.toGMTString();
            }
            if (!path) 
                path = "/";

            if (domain)
                document.cookie = name + "=" + value + expires + "; path=" + path + "; domain=" + domain + ";";
            else
                document.cookie = name + "=" + value + expires + "; path=" + path + ";";
        }
        else
        {
            var name = name + "=";
            var cookies = document.cookie.split(";");
            for(var i=0; i<cookies.length; i++) 
            {
                var c = cookies[i];
                while (c.charAt(0) == " ") 
                    c = c.substring(1, c.length);
                if (c.indexOf(name) == 0) 
                    return c.substring(name.length, c.length);
            }
            return null;
        }
    }
}

//Timer
var timerFn = {
    tick : function( fn,sec ){
        if( fn == null || sec == null || mathFn.toInt(sec) < 0 )
            return null;
            
        sec = sec * 1000;
        
        var timer = setInterval( fn,sec );
        fn();
        return timer;
    },
    tickend : function( timer ){
        if( timer != null )
            clearInterval( timer );
    }
}
//String
var stringFn = {
    substr : function(str, start,len ){
        if( (start + len) >str.length )
        {
            len = str.length - start;
        }
        return str.substr( start,len );
    },
    substring : function( str,start,end ){
        if( end > str.length-1 )
            end = str.length-1;
        return this.substr(str, start,(end+1 - start) );
    },
    toarr : function( str ){
        var arr = [];
        for( var i=0;i<str.length;i++)
            arr[i] = str.charAt( i );
        return arr;
    },
    format : function(){
        var args = arguments;
        var l = args.length;
        if( l == 0 || l == 1 )
            return "";
        var formatStr = args[0];
        
        return formatStr.replace(/\{(\d+)\}/g,function(m,i){
            var index = mathFn.toInt( i );
            if( index + 1 > l - 1 )
                return "";
            return args[index+1]; 
        });
    },
    rndStr : function( len,type){
        var source = "";
        var digit = "0123456789";
        var lc = "abcdefghijklmnopqrstuvwxyz";
        var uc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        switch( type )
        {
            case 1:
                source += digit;
                break;
            case 2:
                source += lc;
                break;
            case 3:                
                source += uc;
                break;
            case 4:
                source += digit;
                source += lc;
                break;                
            case 5:
                source += digit;                
                source += uc;
                break;
            case 6:
                source += lc;
                source += uc;
                break; 
            case 0:
            default:
                source += digit;
                source += lc;
                source += uc;
                break;
        }
        
        var str = "";
        var pos;
        for( var i=0;i<len;i++)
        {
            pos = mathFn.rndInt(2);
            while( pos >= source.length )
                pos = mathFn.rndInt(2);
            str += source.charAt(pos); 
        }        
        return str;
    }
}

//Math
var mathFn = {
    toInt : function( input ){
        return parseInt( input );
    },    
    toFloat : function( input ){
        return parseFloat( input );
    },
    toDate : function( input ){
        return new Date(input);
    },
    rndInt : function(digit,mix,max){
        digit = this.toInt( digit );
        
        var d = digit;
        if( digit < 1 )
            d = 1;
            
        if( digit > 17 )
            d = 17;
        
        var random = Math.random();
        
        var digitStr = "1";
        for( var i=0;i < d ;i++)
            digitStr += "0";
            
        var str = (random * this.toInt( digitStr )).toString(); 
        var result = this.toInt( str );
        if( mix!= null && max != null )
        {
            while( result< mix || result > max )
            {
                result = mathFn.rndInt( digit,max );
            }
        }
        return result;
    }
}

//XML
var xmlFn = {
    createXmlDoc: function()
    {
        var xmlDoc;
        if (window.ActiveXObject)
        {
            xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
            xmlDoc.async = false;
        }
        else if (document.implementation && document.implementation.createDocument)
        {
            xmlDoc = document.implementation.createDocument('', '', null);
            xmlDoc.async = false;
        }
        else
            return null;

        return xmlDoc;
    },
    load: function(url)
    {
        var xmlDoc = xmlFn.createXmlDoc();
        if (xmlDoc != null)
            xmlDoc.load(url);
        return xmlDoc;
    },
    loadXml: function(xmlStr)
    {//不能包含<?xml
        var xmlDoc = xmlFn.createXmlDoc();
        if (xmlDoc != null)
            xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    },
    root: function(xmlDoc)
    {
        if (xmlDoc == null)
            return null;
        return xmlDoc.documentElement;
    },
    nodes: function(xmlDoc, xpath)
    {
        var root = xmlDoc.documentElement;
        return xmlFn.xq(root, xpath);
    },
    xq: function(node, xpath)
    {
        try
        {
            var nodes;
            if (browserFn.ie)
                nodes = node.selectNodes(xpath);
            else
                nodes = node.selectNodes(xpath);

            nodes = $$.array(nodes);
            return nodes;
        }
        catch (e)
        {
            alert(e.message);
        }
    },
    xatt: function(node, _att)
    {
        return node.getAttribute(_att);
    },
    xxml: function(node)
    {
        if (node.innerXML)
            return node.innerXML;
        else if (node.xml)
            return node.xml;
        else if (typeof XMLSerializer != 'undefined')
            return (new XMLSerializer()).serializeToString(node);
        else
            return false;
    },
    xtxt: function(node)
    {
        return node.text;
    }
}

//Ajax
var ajaxFn = {
    getXmlHttpRequest : function(){
        var httpRequest;
        if (window.XMLHttpRequest)
	        httpRequest = new XMLHttpRequest();
        else
        {
	        var MSXML = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
	        for(var n = 0; n < MSXML.length; n ++)
	        {
		        try
		        {
			        httpRequest = new ActiveXObject(MSXML[n]);
			        break;
		        }
		        catch(e)
		        {
		            httpRequest = false;
		        }
	        }
        }
        return httpRequest
    },
    update : function(obj,url,preFn,succFn,errFn){
        if( preFn != "underfined" && preFn != null )
            preFn();
        
        this.req( url,
            function(rsp){
                htmlFn.html( obj,rsp );
                if(succFn!=null)
                    succFn(rsp);
             },
             errFn);
    },
    update_post : function(obj,url,data,preFn,succFn,errFn){
        if( preFn != null )
            preFn();
        this.post( url,data,function(rsp){
                    $$.idObj(obj).html( rsp );
                    if(succFn!=null)
                        succFn(rsp);
                },errFn);
    },
    req : function(url,succFn,errFn,getXml,stateChangeFn){
        this.transfer(url,null,"GET",succFn,errFn,getXml,stateChangeFn)
    },
    post : function(url,data,succFn,errFn,getXml,stateChangeFn){
        this.transfer(url,data,"POST",succFn,errFn,getXml,stateChangeFn)
    },
    transfer : function(url,data,method,succFn,errFn,getXml,stateChangeFn){
        var httpRequest = this.getXmlHttpRequest();
        if( !httpRequest )
        {
            if( errFn )
                errFn( "XMLHttpRequest对象创建错误" );
            return ;
        }
        
        httpRequest.onreadystatechange = function(){
            if( stateChangeFn != null )
                stateChangeFn(httpRequest);
            
            if (httpRequest.readyState == 4)
            {
                if(httpRequest.status >= 200 && httpRequest.status < 400 )
                {
                    if( succFn )
                    {
                        if( getXml == null || !getXml )
                            succFn(httpRequest.responseText);
                        else
                            succFn(httpRequest.responseXML);
                    }
                }
                else if( errFn )
                    errFn( "加载错误,HTTP状态码:[" + httpRequest.status + "]" );
                    
		        delete(httpRequest);
            }
        }
        
        try
        {
            httpRequest.open(method, url, true);
            if (method == 'POST')
            {
                httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
                httpRequest.setRequestHeader("Content-Length",data.length);
            }
            httpRequest.send(data);
        }
        catch(e)
        {
            if( errFn )
                errFn( e.message );
            return ;
        }
    }
}

var tableFn = {
    newTable : function( id,rows,cols,tbCssText,trCssText,tdCssText,txt){
        var table = document.createElement("Table");
        if( id != null )
            table.id = id; 
            
        if( tbCssText != null )
            table.style.cssText = tbCssText;
        if( trCssText == null )
            trCssText = "";
        if( tdCssText == null )
            tdCssText = "";
        if( txt == null )
            txt = "";
            
        if( rows == null )
            rows = 1;
        if( cols == null )
            cols = 1;
        for( var r = 0;r < rows;r++ )
            Table.newRow( table,null,trCssText,tdCssText,cols,txt );
        return table;
        
    },
    newRow : function(table,id,trCssText,tdCssText,cols,txt){
        var row = table.insertRow();
        if( id != null )
            row.id = id;
        if( trCssText != null )
            row.style.cssText = trCssText;
        if( tdCssText == null )
            tdCssText = "";
        if( txt == null )
            txt = "";
        
        for( var c = 0;c < cols;c++ )
            Table.newColumn( row,null,tdCssText,txt );
        return row;
    },
    newColumn : function(row,id,tdCssText,txt){
        var cell = row.insertCell();
        if( tdCssText != null )
            cell.style.cssText = tdCssText;
        if( id != null )
            cell.id = id;
        if( txt != null )
            cell.appendChild( document.createTextNode(txt) );
        return cell;
    }
}

var windowFn = {
    onload : function( func ){//附加onload事件
        if (window.addEventListener) 
            window.addEventListener('load', func, false);
        else if (window.attachEvent)
            window.attachEvent('onload', func);
    }
}


//document 包含的功能
//获取对象的fn
//cookie的fn
//url的fn
//浏览器的fn
Object.extendFn( document,fn);
Object.extendFn( document,cookieFn);
Object.extendFn( document,urlFn);
Object.extendFn( document,browserFn );

//此对象包含所有功能
var $$ = {};
Object.extendFn( $$,ajaxFn );
Object.extendFn( $$,xmlFn );
Object.extendFn( $$,mathFn );
Object.extendFn( $$,stringFn );
Object.extendFn( $$,timerFn );
Object.extendFn( $$,cookieFn );
Object.extendFn( $$,urlFn );
Object.extendFn( $$,checkFn );
Object.extendFn( $$,cssFn );
Object.extendFn( $$,htmlFn );
Object.extendFn( $$,browserFn );
Object.extendFn( $$,posFn );
Object.extendFn( $$,fn );
Object.extendFn( $$,windowFn );
Object.extendFn($$, {
    htmlObj: function(html)
    {
        var id = "htmlDiv_" + Math.random();
        id = id.replace(".", "");

        var obj = $$.idObj(id);
        if (obj == null)
        {
            obj = $$.el("div");
            obj.id = id;
            obj = $$.addel(obj);
            obj.hide();
        }
        obj.html(html);

        var n;
        if ($$.firefox)
            n = $$.idObj(obj.childNodes[1]);
        else
            n = $$.idObj(obj.childNodes[0]);
        return n;
    },
    serializeTarget: function(target)
    {
        if (target == null)
            target = document.forms[0];
        target = $$.idObj(target);
        var els = $$.tagObj("*", target);
        var arr = [];
        els.each(function(element)
        {
            if (!element.name)
                return;
            switch (element.type)
            {
                case "text":
                case "textarea":
                case "hidden":
                    arr[arr.length] = encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value);
                    break;
                case "select-one":
                case "select-multiple":
                    var options = $$.array(element.options);
                    options.each(function(item)
                    {
                        if (item.selected)
                            arr[arr.length] = encodeURIComponent(element.name) + "=" + encodeURIComponent(item.value);
                    });
                    break;
                case "checkbox":
                case "radio":
                    if (element.checked)
                        arr[arr.length] = encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value);
                    break;
                case "file":
                    if (element.value != "")
                        arr[arr.length] = encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value) + "&";
                    break;
                default:
                    arr[arr.length] = encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value)
                    break;
            }
        });
        arr = $$.array(arr);
        var param = "";
        arr.each(function(item)
        {
            if (param.length > 0)
                param += "&";
            param += item;
        });
        return param;
    }
});

var domReadyFn = {
    domReady: (function(){
            var load_events = [],load_timer,script,done,exec, old_onload,init = function(){
                done = true;
                clearInterval(load_timer);
                while (exec = load_events.shift())
                    exec();

                if (script) 
                    script.onreadystatechange = '';
            };

            return function(func)
            {
                if (done) 
                    return func();

                if (!load_events[0])
                {
                    // for Mozilla/Opera9
                    if (document.addEventListener)
                        document.addEventListener("DOMContentLoaded", init, false);

                    // for Internet Explorer
                    /*@cc_on@*/
                    /*@if (@_win32)
                    document.write("<script id=__ie_onload defer src=//0><\/scr" + "ipt>");
                    script = document.getElementById("__ie_onload");
                    script.onreadystatechange = function()
                    {
                        if (this.readyState == "complete")
                            init(); // call the onload handler
                    };
                    /*@end@*/

                    // for Safari
                    if (/WebKit/i.test(navigator.userAgent))
                    { // sniff
                        load_timer = setInterval(function()
                        {
                            if (/loaded|complete/.test(document.readyState))
                                init(); // call the onload handler
                        }, 10);
                    }

                    // for other browsers set the window.onload, but also execute the old window.onload
                    old_onload = window.onload;
                    window.onload = function()
                    {
                        init();
                        if (old_onload) 
                            old_onload();
                    };
                }

                load_events.push(func);
            }
        })()
}

Object.extendFn($$, domReadyFn);

$$.ready = $$.domReady;

//firefox兼容
if( $$.firefox )
{
    //文档兼容 
    HTMLDocument.prototype.__defineGetter__("all",function(){ 
        return this.getElementsByName("*");
    }); 
    HTMLFormElement.constructor.prototype.item = function(s){ 
        return this.elements[s];
    }; 
    HTMLCollection.prototype.item = function(s){ 
        return this[s];
    }; 
    
    //事件兼容 
    window.constructor.prototype.__defineGetter__("event",function(){ 
        for(var o=arguments.callee.caller,e=null;o!=null;o=o.caller){ 
            e=o.arguments[0]; 
            if(e&&(e instanceof Event)) 
                return e;
        } 
        return null;
    }); 
    window.constructor.prototype.attachEvent = HTMLDocument.prototype.attachEvent = HTMLElement.prototype.attachEvent = function(e,f){ 
        this.addEventListener(e.replace(/^on/i,""),f,false);
    }; 
    window.constructor.prototype.detachEvent=HTMLDocument.prototype.detachEvent = HTMLElement.prototype.detachEvent = function(e,f){ 
        this.removeEventListener(e.replace(/^on/i,""),f,false);
    };
    //Event
    window.Event.constructor.prototype.__defineGetter__("srcElement",function(){ 
        return this.target;
    }); 
    window.Event.constructor.prototype.__defineSetter__("returnValue",function(b){ 
        if(!b)
            this.preventDefault();
    }); 
    window.Event.constructor.prototype.__defineSetter__("cancelBubble",function(b){ 
        if(b)
            this.stopPropagation();
    }); 
    window.Event.constructor.prototype.__defineGetter__("fromElement",function(){ 
        var o=(this.type=="mouseover"&&this.relatedTarget)||(this.type=="mouseout"&&this.target)||null; 
        if(o) 
            while(o.nodeType!=1) 
                o=o.parentNode; 
        return o;
    }); 
    window.Event.constructor.prototype.__defineGetter__("toElement",function(){ 
        var o=(this.type=="mouseover"&&this.target)||(this.type=="mouseout"&&this.relatedTarget)||null; 
        if(o) 
            while(o.nodeType!=1) 
                o=o.parentNode; 
        return o;
    }); 
    window.Event.constructor.prototype.__defineGetter__("x",function(){ 
        return this.pageX;
    }); 
    window.Event.constructor.prototype.__defineGetter__("y",function(){ 
        return this.pageY;
    }); 
    window.Event.constructor.prototype.__defineGetter__("offsetX",function(){ 
        return this.layerX;
    }); 
    window.Event.constructor.prototype.__defineGetter__("offsetY",function(){ 
        return this.layerY;
    });
    
    //Node
    window.Node.prototype.replaceNode = function(o){ 
        this.parentNode.replaceChild(o,this);
    } 
    window.Node.prototype.removeNode = function(b){ 
        if(b) 
            return this.parentNode.removeChild(this); 
        var range=document.createRange(); 
        range.selectNodeContents(this); 
        return this.parentNode.replaceChild(range.extractContents(),this);
    } 
    window.Node.prototype.swapNode = function(o){ 
        return this.parentNode.replaceChild(o.parentNode.replaceChild(this,o),this);
    } 
    window.Node.prototype.contains=function(o){ 
        return o?((o==this)?true:arguments.callee(o.parentNode)):false;
    } 
    
    //HTMLElement
    window.HTMLElement.prototype.__defineGetter__("parentElement",function(){ 
        return (this.parentNode==this.ownerDocument)?null:this.parentNode;
    }); 
    window.HTMLElement.prototype.__defineGetter__("children",function(){ 
        var c=[]; 
        for(var i=0,cs=this.childNodes;i<cs.length;i++){ 
            if(cs[i].nodeType==1) 
                c.push(cs[i]);
        } 
        return c;
    }); 
    window.HTMLElement.prototype.__defineGetter__("canHaveChildren",function(){ 
        return !/^(area|base|basefont|col|frame|hr|img|br|input|isindex|link|meta|param)$/i.test(this.tagName);
    }); 
    window.HTMLElement.prototype.__defineSetter__("outerHTML",function(s){ 
        var r = this.ownerDocument.createRange(); 
        r.setStartBefore(this); 
        void this.parentNode.replaceChild(r.createContextualFragment(s),this); 
        return s;
    }); 
    window.HTMLElement.prototype.__defineGetter__("outerHTML",function(){
        var as = this.attributes; 
        var str="<"+this.tagName; 
        for(var i=0,al=as.length;i<al;i++)
        { 
            if(as[i].specified) 
                str+=" "+as[i].name+"=\""+as[i].value+"\"";//重新拼属性
        }
        return !this.canHaveChildren ? str + " />" : str + ">" + this.innerHTML + "</"+this.tagName+">";
    }); 
    window.HTMLElement.prototype.__defineSetter__("innerText",function(s){ 
        return this.innerHTML = document.createTextNode(s);
    }); 
    window.HTMLElement.prototype.__defineGetter__("innerText",function(){ 
        var r = this.ownerDocument.createRange(); 
        r.selectNodeContents(this); 
        return r.toString();
    }); 
    window.HTMLElement.prototype.insertAdjacentElement = function(s,o){ 
        return (s=="beforeBegin"&&this.parentNode.insertBefore(o,this))||(s=="afterBegin"&&this.insertBefore(o,this.firstChild))||(s=="beforeEnd"&&this.appendChild(o))||(s=="afterEnd"&&((this.nextSibling)&&this.parentNode.insertBefore(o,this.nextSibling)||this.parentNode.appendChild(o)))||null;
    } 
    window.HTMLElement.prototype.insertAdjacentHTML = function(s,h){ 
        var r=this.ownerDocument.createRange(); 
        r.setStartBefore(this); 
        this.insertAdjacentElement(s,r.createContextualFragment(h));
    } 
    window.HTMLElement.prototype.insertAdjacentText = function(s,t){ 
        this.insertAdjacentElement(s,document.createTextNode(t));
    } 
    
    //XMLDocument
    XMLDocument.prototype.loadXML = function(xmlString){ 
        var cs = this.childNodes;
        for(var i=0;i<cs.length;i++) 
            this.removeChild(cs[i]); 
        this.appendChild(this.importNode((new DOMParser()).parseFromString(xmlString,"text/xml").documentElement,true));
    }
    XMLDocument.prototype.selectNodes = function(xpath,xNode){
        if( xNode==null )
            xNode = this;
        var oNSResolver = this.createNSResolver(this.documentElement)
        var aItems = this.evaluate(xpath, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);        
        var aResult = [];
        for( var i = 0; i < aItems.snapshotLength; i++)
            aResult[i] = aItems.snapshotItem(i);
        return aResult;
    }
    XMLDocument.prototype.selectSingleNode = Element.prototype.selectSingleNode = function(xpath){ 
        return this.selectNodes(xpath)[0];
    } 
    
    //Element
    Element.prototype.selectNodes = function(xpath){
        if(this.ownerDocument.selectNodes)
           return this.ownerDocument.selectNodes(xpath, this);
        else
            throw "For XML Elements Only";
    }
    
    //xml属性
    XMLDocument.prototype.__proto__.__defineGetter__("xml",function(){ 
        try{ 
            return new XMLSerializer().serializeToString(this);
        } 
        catch(e)
        { 
            return document.createElement("div").appendChild(this.cloneNode(true)).innerHTML;
        }
    }); 
    Element.prototype.__proto__.__defineGetter__("xml",function(){ 
        try{ 
            return new XMLSerializer().serializeToString(this);
        } 
        catch(e)
        { 
            return document.createElement("div").appendChild(this.cloneNode(true)).innerHTML;
        }
    }); 
    
    //text属性
    XMLDocument.prototype.__proto__.__defineGetter__("text",function(){ 
        return this.firstChild.textContent;
    }); 
    Element.prototype.__proto__.__defineGetter__("text",function(){ 
        return this.textContent;
    }); 
    Element.prototype.__proto__.__defineSetter__("text",function(s){ 
        return this.textContent=s;
    });
}

