(function(wnd, undef){

    //复制json对象
    function min_copyjson(json)
    {
        return JSON.parse(JSON.stringify(json));
    }

    //json对象转字符串
    function min_jsontostr(json) {
        return JSON.stringify(json);
    }

    //字符串转json对象
    function min_strtojson(str) {
        return JSON.parse(str);
    }

    //字符串转整型 def:转换失败时返回的默认值
    function min_strtoint(str, def) {
        var i = parseInt(str);
        if (i == 0) {
            return 0;
        };
        if (!i) { //=0也会进来       
            if (!def) {
                def = 0;
            };
            i = def;
        }
        return i;
    };

    //整型转字符串
    function min_inttostr(i) {
        return i.toString();
    };    

    //整除
    function min_div(i, b) 
    {
        if (!b) {
            return parseInt(i);
        }
        return parseInt(i / b);
    };

    //取余数
    function min_mod(a, b){
        return a % b;
    };

    //取绝对值
    function min_abs(b) {
        return Math.abs(b);
    }; 

    //取随机数
    function min_random(min, max) {
        var Range = max - min;
        var Rand = Math.random();
        return (min + Math.round(Rand * Range));
    };
    //取随机数1
    function min_random1(num) {
        return parseInt(Math.random()*num);
    };
	
    //随机字符串
    function min_randomChar(length){
        var x = "0123456789";
        var y = "qwertyuioplkjhgfdsazxcvbnm";
        var z = "QWERTYUIOPLKJHGFDSAZXCVBNM";
        var tmp = "";        
        for (var i = 0; i < length; i++) {
            switch(min_random(0, 2)) {
                case 0:
                    tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
                    break;                
                case 1:
                    tmp += y.charAt(Math.ceil(Math.random()*100000000)%y.length);
                    break;
                case 2:
                    tmp += z.charAt(Math.ceil(Math.random()*100000000)%z.length);
                    break;               
                default:
                    break; 
            }            
        }
        // var timestamp = new Date().getTime();
        // return timestamp + tmp;
        return tmp;
    }

    //取长度
    function min_length(key) {
        if (typeof(key) != "string") {
            var key = key + "";
        }
        return key.length;
    } 

    //字符全替换
    function min_replaceAll(str, str_old, str_new, ignoreCase) 
    {  
        if (!RegExp.prototype.isPrototypeOf(str_old)) {  
            return str.replace(new RegExp(str_old, (ignoreCase ? "gi": "g")), str_new);  
        } else {  
            return str.replace(str_old, str_new);  
        }  
    }   

    //取本地当前时间，格式yyyy-MM-dd HH:MM:SS
    function min_now() 
    {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds();
        return currentdate;
    }    

    //本地存储数据
    function min_writefile_gameid(msg, gameid, fileid) {
        localStorage.setItem("file_" + gameid + "_" + fileid, msg);
    }

    //读取本地数据
    function min_readfile_gameid(gameid, fileid) {
        return localStorage.getItem("file_" + gameid + "_" + fileid);
    }

    //取当前页面url中的参数值 def:没取到时返回的默认值
    function min_getQueryString(name, def) {
        var self = window;
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = self.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2])
        } else {
            if (def) {
                return def;
            } else {
                return null;
            }
        }
    }

    //获取当前页面的路径
    function min_getUrlRootPath() {
        var curWwwPath = window.location.host;
        var pathName = window.location.pathname;
        return curWwwPath + pathName.substr(0,pathName.lastIndexOf('/'));
    }

    //设置cookie
    function min_setCookie(name, value, exp_minute) {
        if (!exp_minute) {
            exp_minute = 20; //默认时效20分钟
        }
        var exp = new Date();
        exp.setTime(exp.getTime() + exp_minute*60*1000);
        document.cookie = name + "=" + value + ";expires=" + exp.toGMTString()+';path=/';
    }

    //读取cookie
    function min_getCookie(name) {
        var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
        if(arr != null)
            return arr[2];
        return null;
    }

    //删除cookie
    function min_delCookie(name) {
        var value = min_getCookie(name);
        if (value) {
            min_setCookie(name, value, 0);
        }
    }

    //获取一个dom
    function min_getdom(id) 
    {
        return document.getElementById(id);
    };    

    //设置一个dom属性值 id：dom、或dom的id、或实列，key：属性，val：值
    function min_setdom(id, key, val) {
        var obj;
        if (typeof(id) == 'string') {
            obj = min_getdom(id);
        } 
        else {
            obj = id;
        }
        obj.setAttribute(key, val);
    }

    //添加一段innerHTML
    function min_uphtml(id, str, isadd) {
        /*
        setAttribute是设置网页元素的属性，就是在标签里内如<img />标签的src属性。
        innerHTML不是属性，只是JS里内代表一个双标记中间的文本，如:<span> </span>中间的字符。
        */
        var obj = window.document.getElementById(id);
        if (isadd) {
            obj.innerHTML = obj.innerHTML + str;
        } 
        else {
            obj.innerHTML = str;
        }
    }

    //新建一个定时器每隔time毫秒执行一次func函数，函数返回定时器id
    function min_ontime(func, time) 
    {
        return setInterval(func, time); 
    }

    //新建一个定时器time毫秒后执行一次func函数（只执行一次），函数返回定时器id
    function min_ontimeout(func, time) 
    {
        return setTimeout(func, time); 
    }

    //关闭定时器id为timerid的定时器
    function min_closetime(timerid) 
    {
        return clearTimeout(timerid); 
    }

    //encode转码
    function min_encode(s)
    {
        return encodeURIComponent(s);
    }

    //decode解码
    function min_decode(s)
    {
        return decodeURIComponent(s);
    }          

    //新建一个tcp连接
    function min_tcp(config) 
    {
        var ws = new WebSocket("ws://" + config.ipport); //"127.0.0.1:5414"

        //连接上服务器后触发的事件
        if (config.onopen) {
            ws.onopen = config.onopen; 
        };

        //收到服务器发来的数据包后触发的事件，onmessage函数会有一个底层的msg参数，其中msg.data才是服务器发过来的业务数据
        if (config.onmessage) {
            ws.onmessage = config.onmessage; 
        };

        //断开与服务器的连接后触发的事件
        if (config.onclose) {
            ws.onclose = config.onclose; //断开连接的事件
        };

        return ws;
    } 

    //http请求
    function min_http(config) {
    /*
    config = 
    {
        url: "http://127.0.0.1:5414/index.html",  
        type: "POST",     //GET or POST 方法
        data: "",         //请求的数据               
        success: func_callback_succ, //请求成功后的回调函数function(data,status,callbackdata)
        error: func_callback_err,    //请求失败后的回调函数function(data,status)
        callbackdata: "",            //作为回调函数第三个参数带入回调函数的数据
        //enurl: 0,         //是否encodeURIComponent转码, 默认0不转码
        //deurl: 0,         //是否decodeURIComponent解码，默认0不解码
        debugLog: false,  //是否输出debug日志，默认false                 
        method: "(OPTIONAL) True for async and False for Non-async | By default its Async"
    }
    */
        if (!config.debugLog) {
            config.debugLog = false;
        }
        if (!config.enurl) {
            config.enurl = 0;
        }
        if (!config.deurl) {
            config.deurl = 0;
        }
        if (!config.method) {
            config.method = true;
        }        

        if (!config.url) {
            if (config.debugLog == true) {
                console.log("No Url!");
            }
            return;
        };

        if (!config.type) {
            if (config.debugLog == true) {
                console.log("No Default type (GET/POST) given!");
            }
            return;
        }        

        var xmlhttp = initXMLhttp();

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200 && config.success) 
            {
                var responseText = mydecodeURIComponent(xmlhttp.responseText, config.deurl);
                if (!config.callbackdata) {			     
                    config.success(responseText, xmlhttp.readyState); 		     
                }
                else {
                    config.success(responseText, xmlhttp.readyState, config.callbackdata);
                }                    
                if (config.debugLog == true) {
                    console.log("SuccessResponse");
                }
                if (config.debugLog == true) {
                    console.log("Response Data:" + xmlhttp.responseText);
                }
            }
            else 
            {
                if (xmlhttp.readyState == 4 && config.error) 
                {
                    if (!config.callbackdata) {			     
                        config.error(xmlhttp.readyState, xmlhttp.status); 			     
                    }
                    else {
                        config.error(xmlhttp.readyState, xmlhttp.status, config.callbackdata); 
                    }
                }
                if (config.debugLog == true) {
                    console.log("FailureResponse --> readyState:" + xmlhttp.readyState + ",  Status:" + xmlhttp.status);                
                }
            }
        }

        var sendString = [],
        sendData = config.data;
        if (typeof sendData === "string") {
            var tmpArr = String.prototype.split.call(sendData, '&');
            for (var i = 0, j = tmpArr.length; i < j; i++) {
                var datum = tmpArr[i].split('=');
                if (datum[1]) {
                    sendString.push(myencodeURIComponent(datum[0], config.enurl) + "=" + myencodeURIComponent(datum[1], config.enurl));
                } 
                else {
                    sendString.push(myencodeURIComponent(datum[0], config.enurl));
                }
            }
        } 
        else if (typeof sendData === 'object' && !(sendData instanceof String || (FormData && sendData instanceof FormData))) {
            for (var k in sendData) {
                var datum = sendData[k];
                if (Object.prototype.toString.call(datum) == "[object Array]") {
                    for (var i = 0, j = datum.length; i < j; i++) {
                        sendString.push(myencodeURIComponent(k, config.enurl) + "[]=" + myencodeURIComponent(datum[i], config.enurl));
                    }
                } 
                else {
                    sendString.push(myencodeURIComponent(k, config.enurl) + "=" + myencodeURIComponent(datum, config.enurl));
                }
            }
        }
        sendString = sendString.join('&');

        if (config.type == "GET") {
            var g;
            var i = config.url.lastIndexOf("?");
            if (i > 8) {
                g = "&";
            } else {
                g = "?";
            }
            var ddata = new Date().getMilliseconds();
            if (sendString == "") {
                sendString = '#dfw1977=' + (ddata + min_random(1, 99999) * 1000);
            } else {
                sendString = sendString + '#dfw1977=' + (ddata + min_random(1, 99999) * 1000);
            }
            xmlhttp.open("GET", config.url + g + sendString, config.method);
            xmlhttp.send();

            if (config.debugLog == true) {
                console.log("GET fired at:" + config.url + "?" + sendString);
            }
        }
        if (config.type == "POST") {
            xmlhttp.open("POST", config.url, config.method);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.send(sendString);

            if (config.debugLog == true) {
                console.log("POST fired at:" + config.url + " || Data:" + sendString);
            }
        }
    }

    function initXMLhttp() {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            //code for IE7,firefox chrome and above
            xmlhttp = new XMLHttpRequest();
        } else {
            //code for Internet Explorer
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xmlhttp;
    }

    //转码
    function myencodeURIComponent(s, ifif)
    {
        if (ifif == 1) {
            return min_encode(s);
        } else {
            return s;
        }
    }

    //解码
    function mydecodeURIComponent(s, ifif) 
    {
        if (ifif == 1) {
            return min_decode(s);
        } else {
            return s;
        }

    }

    //在数组中根据元素值查找下标
    function min_ary_indexof(array1, val, name) 
    {              
        for (var i = 0; i < array1.length; i++) 
        {
            if (!name)
            {
                if (array1[i] == val) 
                    return i;
            }
            else
            {
                if (array1[i][name] == val) 
                    return i;
            } 
        }  
        return -1;  
    };  

    //在数组中根据值删除元素
    function min_ary_delval(array1, val, name) 
    {  
        var index = min_ary_indexof(array1, val, name);  
        if (index > -1) 
        {  
            array1.splice(index, 1);  
        }  
    };         

    //在数组中根据下标删除诺干个元素
    function min_ary_delfromto(array1, from, to)
    {
        var rest = array1.slice((to || from) + 1 || array1.length);
        array1.length = from < 0 ? array1.length + from : from;
        array1.push.apply(array1, rest);
    };

    //在数组中删除某一对象元素
    function min_ary_delobj(array1, object)
    {
        for (var i = 0; i < array1.length; ++i)
        {
            if (array1[i] === object)
            {
                array1.splice(i, 1); 
                break;
            }
        }
    };

    //数组包含
    function min_ary_include(aryparent, arychild){
        for (var i = 0; i < arychild.length; i++) {
            var found = false;
            for (var j = 0; j < aryparent.length; j++) {
                if (aryparent[j] == arychild[i]){
                    found = true;
                    break;
                }
            }
            if (!found){
                return false;
            }
        }
        return true;
    };    

    //数组相减
    function min_ary_deduct(aryparent, arychild){
        var re = [];
        for (var i = 0; i < aryparent.length; i++){
            var found = false;
            for (var j = 0; j < arychild.length; j++){
                if (aryparent[i] == arychild[j]){
                    found = true;
                    break;
                }
            }
            if (!found){
                re.push(aryparent[i])
            }
        }
        return re;
    };

    //是否存在指定函数 
    function min_ExitsFunction(funcName) 
    {
        try 
        {
            if (typeof(funcName) == "function") 
            {
                return true;
            }
        } 
        catch(e) 
        {}
        return false;
    }

    //（按顺序）加载js文件
    function min_loadJsFile(str_jsfile, func_succ, NoRandomFlag) 
    {
        var domScript = document.createElement('script');
        if (!NoRandomFlag)
        {
            // str_jsfile = str_jsfile + '?' + Math.random() * 10000;
            // str_jsfile = str_jsfile + '?' + min_random(1, 10000000);
            str_jsfile = str_jsfile + '?' + min_timestamp();
        }
        domScript.src = str_jsfile;
        func_succ = func_succ || function(){};
        domScript.onload = domScript.onreadystatechange = function() {
            if (!this.readyState || 'loaded' === this.readyState || 'complete' === this.readyState) {
              func_succ();
              this.onload = this.onreadystatechange = null;
              this.parentNode.removeChild(this);
            }
          }
        document.getElementsByTagName('head')[0].appendChild(domScript);        
    }

    //生成一个GUID
    function min_guid() 
    {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);});
    }

    //获取时间戳
    function min_timestamp()
    {
        return new Date().getTime();
    }
     

    wnd.min_copyjson  = min_copyjson;   //复制json对象
    wnd.min_jsontostr = min_jsontostr;  //json转字符串
    wnd.min_strtojson = min_strtojson;  //字符串转json
    wnd.min_inttostr  = min_inttostr;   //整型转字符型
    wnd.min_strtoint  = min_strtoint;   //字符型转整型 
  
    wnd.min_div = min_div;       //整除
    wnd.min_mod = min_mod;       //取余数
    wnd.min_abs = min_abs;       //取绝对值 
    wnd.min_random = min_random; //取随机数    
	wnd.min_random1 = min_random1; //取随机数1    
    wnd.min_randomChar = min_randomChar; //随机字符串
    wnd.min_length = min_length; //取长度
    wnd.min_replaceAll = min_replaceAll; //字符全替换
    
    wnd.min_now  = min_now;      //取本地当前时间
    wnd.min_guid = min_guid;     //生成一个GUID

    wnd.min_getQueryString = min_getQueryString;  //取当前页面url中的参数值
    wnd.min_getUrlRootPath = min_getUrlRootPath;  //获取当前页面的路径
        
    wnd.min_setCookie = min_setCookie; //设置cookie    
    wnd.min_getCookie = min_getCookie; //读取cookie    
    wnd.min_delCookie = min_delCookie; //删除cookie

    wnd.min_getdom = min_getdom; //获取一个dom
    wnd.min_setdom = min_setdom; //设置一个dom属性值   
    wnd.min_uphtml = min_uphtml; //添加一段innerHTML

    wnd.min_ontime    = min_ontime;     //新建一个周期性的定时器
    wnd.min_ontimeout = min_ontimeout;  //新建一个一次性的定时器
    wnd.min_closetime = min_closetime;  //关闭定时器 

    wnd.min_writefile_gameid = min_writefile_gameid; //本地存储数据
    wnd.min_readfile_gameid  = min_readfile_gameid;  //读取本地数据

    wnd.min_encode = min_encode; //encodeURIComponent转码
    wnd.min_decode = min_decode; //decodeURIComponent解码

    wnd.min_tcp  = min_tcp;      //新建一个tcp连接
    wnd.min_http = min_http;     //http请求
    
    wnd.min_ary_indexof   = min_ary_indexof;   //在数组中根据元素值查找下标    
    wnd.min_ary_delval    = min_ary_delval;    //在数组中根据值删除元素
    wnd.min_ary_delfromto = min_ary_delfromto; //在数组中根据下标删除诺干个元素
    wnd.min_ary_delobj    = min_ary_delobj;    //在数组中删除某一对象元素
    wnd.min_ary_include   = min_ary_include;   //数组包含
    wnd.min_ary_deduct    = min_ary_deduct;    //数组相减

    wnd.min_ExitsFunction = min_ExitsFunction; //是否存在函数    
    wnd.min_loadJsFile    = min_loadJsFile;    //加载js文件

    wnd.min_guid = min_guid; //生成一个GUID    
    wnd.min_timestamp = min_timestamp; //获取时间戳
})(window);













