﻿Edo = {};
Edo.util = {};
Edo.util.Cookie = {
    get: function(sName){	    
        var aCookie = document.cookie.split("; ");
        var lastMatch = null;
        for (var i=0; i < aCookie.length; i++)
        {	    
            var aCrumb = aCookie[i].split("=");
            if (sName == aCrumb[0]){
                lastMatch = aCrumb;                
            }
        }
        if(lastMatch){
            var v = lastMatch[1];
            if(v === undefined) return v;
            return unescape(v);	            
        }	            
        return null;
    },  
    set: function(name, value) {          
    
        var argv = arguments; 
        var argc = arguments.length; 
        var expires = (argc > 2) ? argv[2] : null; 
        
        var LargeExpDate = new Date (); 
        if(expires!=null) 
        {             
            LargeExpDate.setTime(LargeExpDate.getTime() + (expires*1000*3600*24));         
        }
        
        document.cookie = name + "=" + escape (value)+((expires == null) ? "" : ("; expires=" +LargeExpDate.toGMTString()))+";path=/"; 
    }, 
    del: function(name) { 
        var expdate = new Date(); 
        expdate.setTime(expdate.getTime() - (86400 * 1000 * 1)); 
        this.set(name, "", -100);
    }
};

if(!window.XMLHttpRequest){
    window.XMLHttpRequest = function(){
        var progIDs = ['Msxml2.XMLHTTP','Microsoft.XMLHTTP'];
        for(var i=0; i<progIDs.length; i++){
            try{
                var xmlHttp = new ActiveXObject(progIDs[i]);
                return xmlHttp;
            }catch(ex){
            }
        }
        return null;
    }
}
function emptyFn(){}
(function(){
function getUrlParam( hs ) {
    var s = [];
    for ( var j in hs) {
        var v = hs[j];
        if(typeof(v) == 'object'){
            v = Edo.util.Json.encode(v);
        }
        s.push(encodeURIComponent(j) + "=" + encodeURIComponent(v));
    }
    return s.join("&");
}    
function apply(o, c, defaults){
    if(defaults){
        apply(o, defaults);
    }
    if(o && c && typeof c == 'object'){
        for(var p in c){
            o[p] = c[p];
        }
    }
    return o;
};
function abort(){   
    if(this._timer){
        window.clearTimeout(this._timer);
        this._timer = null;
    }
    var http = this.request;
    if(http){       
        http.onreadystatechange = emptyFn;
        http.abort();
        //this.request = null;
        http.onFail(0, this);                   //out失败:0                          
    }
}
function onreadystatechange(http){
    var http = this.request;
    if (http.readyState === 4) {
        if(http.status === 200) {           
            this.onSuccess(http.responseText, this);        
        }else{
            this.onFail(http.status, this);
        }
        http.onreadystatechange = emptyFn;  
    }
}
Edo.util.Ajax = {
    request: function(config){                    
    
        var xmlHttp = new XMLHttpRequest();        
        var c = apply({
            type: "get",            
            url: null,
            timeout: 0,
            contentType: "application/x-www-form-urlencoded",    
            async: true,
            params: null,     //key-value形式,value必须为字符串对象(jsonString).
            onSuccess: emptyFn,
            onFail: emptyFn,
            onOut: emptyFn,
            request: xmlHttp,
            abort: abort
        }, config);
                
        var data = getUrlParam(c.params);
        
        if (c.type.toLowerCase() == "post"){
            xmlHttp.open(c.type, c.url, c.async);
            xmlHttp.setRequestHeader("Content-Type", c.contentType);
        }else{
            if(c.params) c.url += ((c.url.indexOf("?") > -1) ? "&" : "?") + data;
            c.url += ((c.url.indexOf("?") > -1) ? "&" : "?") + '_$nocache='+new Date().getTime();
            xmlHttp.open(c.type, c.url, c.async);
        }
        xmlHttp.onreadystatechange = function(){
            onreadystatechange.call(c);
        }        
        
	    if (c.timeout > 0){
		    c._timer = window.setTimeout(function(){
                c.onOut(c);
		    }, c.timeout);
        }
	    try {	    
		    xmlHttp.send(data);		    
	    } catch(e) {
            c.onFail(1000, c);//没有正确调用成功 1000	        
	    }
	    return c;
    }
}    
})();
/**
    @name Edo.util.Json
    @class 
    @description Json
*/
Edo.util.Json = new (function(){
    var useHasOwn = !!{}.hasOwnProperty,
        isNative = function() {
            var useNative = null;

            return function() {
                if (useNative === null) {
                    useNative = Edo.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]';
                }
        
                return useNative;
            };
        }(),
        pad = function(n) {
            return n < 10 ? "0" + n : n;
        },
        doDecode = function(json){
            return eval("(" + json + ')');    
        },
        doEncode = function(o){
            if(typeof o == "undefined" || o === null){
                return "null";
            }else if(Edo.isArray(o)){
                return encodeArray(o);
            }else if(Object.prototype.toString.apply(o) === '[object Date]'){
                return Edo.util.Json.encodeDate(o);
            }else if(typeof o == "string"){
                return encodeString(o);
            }else if(typeof o == "number"){
                return isFinite(o) ? String(o) : "null";
            }else if(typeof o == "boolean"){
                return String(o);
            }else {
                var a = ["{"], b, i, v;
                for (i in o) {
                    if(!useHasOwn || o.hasOwnProperty(i)) {
                        v = o[i];
                        switch (typeof v) {
                        case "undefined":
                        case "function":
                        case "unknown":
                            break;
                        default:
                            if(b){
                                a.push(',');
                            }
                            a.push(doEncode(i), ":",
                                    v === null ? "null" : doEncode(v));
                            b = true;
                        }
                    }
                }
                a.push("}");
                return a.join("");
            }    
        },
        m = {
            "\b": '\\b',
            "\t": '\\t',
            "\n": '\\n',
            "\f": '\\f',
            "\r": '\\r',
            '"' : '\\"',
            "\\": '\\\\'
        },
        encodeString = function(s){
            if (/["\\\x00-\x1f]/.test(s)) {
                return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                    var c = m[b];
                    if(c){
                        return c;
                    }
                    c = b.charCodeAt();
                    return "\\u00" +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + s + '"';
        },
        encodeArray = function(o){
            var a = ["["], b, i, l = o.length, v;
                for (i = 0; i < l; i += 1) {
                    v = o[i];
                    switch (typeof v) {
                        case "undefined":
                        case "function":
                        case "unknown":
                            break;
                        default:
                            if (b) {
                                a.push(',');
                            }
                            a.push(v === null ? "null" : Edo.util.Json.encode(v));
                            b = true;
                    }
                }
                a.push("]");
                return a.join("");
        };

    this.encodeDate = function(o){
        //return 'new Date('+o.getTime()+')';
        
        return '"' + o.getFullYear() + "-" +
                pad(o.getMonth() + 1) + "-" +
                pad(o.getDate()) + "T" +
                pad(o.getHours()) + ":" +
                pad(o.getMinutes()) + ":" +
                pad(o.getSeconds()) + '"';
    };
    
    this.encode = function() {
        var ec;
        return function(o) {
            if (!ec) {
                // setup encoding function on first access
                ec = isNative() ? JSON.stringify : doEncode;
            }
            return ec(o);
        };
    }();

    this.decode = function() {
        var dc;
        return function(json) {
            if (!dc) {
                // setup decoding function on first access
                dc = isNative() ? JSON.parse : doDecode;
            }
            return dc(json);
        };
    }();

})();
Edo.isArray = function(v){
    return Object.prototype.toString.apply(v) === '[object Array]';
}
/**
    @name Edo.util.Template
    @class 
    @description HTML模板生成类
*/ 
Edo.util.Template = function(tpl){
    if(tpl) this.set(tpl);
}
Edo.util.Template.prototype = {
    tagRe: /(?:<%)((\n|\r|.)*?)(?:%>)/ig,
    
    load: function(o){
        if(typeof o == 'string') o = {url: o};
        o = Edo.apply({
            url: '',
            type: 'get',
            nocache: false,
            async: false,
            onSuccess: this.onSuccess.bind(this),
            onFail: this.onFail.bind(this)
        }, o);        
        Expo.util.Ajax.request(o);
        return this;
    },
    onSuccess: function(text){
        this.set(text);
    },
    onFail: function(code){
        
    },
    
    /**
        @name Edo.util.Template#set
        @function 
        @view set( tpl )
        @description 设置模板字符串
        @param {String} tpl 模板字符串
    */  
    set: function(tpl){           
        this.tpl = tpl;
             
        var evals = [];
        var re = this.tagRe;
        
        var ret;
        while ((ret = re.exec(tpl)) != null){
            evals[evals.length] = ret;
        }

        this.fnId = '___TEMPLATE_FN_'+new Date().getTime()+Edo.util.Template.id++;
        var sb = ['window["'+this.fnId+'"] = function (sArr, fnName, args){ ',
                    '\nvar _ = [];var __;\nif(fnName) {eval(fnName+".apply(this, args)"); return _.join("")};'
                    ];
                    
        var start = 0, str, evstr, strArr = [];
        
        for(var i=0,l=evals.length; i<l; i++){
            var ev = evals[i];
            
            str = tpl.substring(start, ev.index);
            
            
            
            if(str){
                var len = strArr.length;
                strArr[len] = str;
                sb[sb.length] = "\n_[_.length] = sArr["+len+"]";
            }
            evstr = ev[1];
            
            if(evstr.charAt(0) == '='){
                sb[sb.length] = "\n__"+evstr;
                sb[sb.length] = "\n_[_.length]=__";
            }else{
                sb[sb.length] = "\n"+evstr;
            }
            
            start = ev.index + ev[0].length;// ev.lastIndex;
        }
        str = tpl.substring(start, tpl.length);
        if(str){
            var len = strArr.length;
            strArr[len] = str;
            sb[sb.length] = "\n_[_.length] = sArr["+len+"]";
        }
        
        sb[sb.length] = '\nreturn _.join("");\n}';
        var fn = sb.join('');        
        
        this.strArr = strArr;                
        
        eval(fn);
        return this;
    }, 
    call: function(name){
        if(this.fnId && name){
            var args = Array.apply(null, arguments);
            args.shift();            
            return window[this.fnId].call(null, this.strArr, name, args);
        }
    },
    /**
        @name Edo.util.Template#run
        @function 
        @view run( data )
        @description 使用数据对象, 根据此模板逻辑, 生成字符串
        @param {Object} data 数据对象
    */  
    run: function(data){
        if(this.fnId){
        
            return window[this.fnId].call(data, this.strArr);
        }
    }
}
Edo.util.Template.id = 1000;
///////////////////////////////
function ismail(mail) {
    var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(mail)) return true;
    else {return false;}
} 
Edo.getParams = function(s){
    s = s || location.search;
    var o = {};
    if(s){
        var ss = s;
        if(s.indexOf('#') == 0 || s.indexOf('?') == 0){
            ss = s.substring(1)
        }        
        ss = ss.split('&');
        for(var i=0; i<ss.length; i++){
            var pv = ss[i].split('=');
            o[pv[0]] = pv[1];
        }
    }    
    return o;
}
Edo.setParams = function(ps){    
    ps = ps || {};
    var sb = [];
    for(var p in ps){
        sb[sb.length] = p+'='+ps[p];
    }
    return sb.join('&');    
}
function get(name){
    var els = document.getElementsByName(name);
    return els[0];
}
function getbyId(id){
    return document.getElementById(id);
}